Tries
A tree of letters: words that share a start share a path, so prefix questions take only as long as the prefix.
Spot it
Signals in the questionMany words and questions about prefixes ("starts with").
Autocomplete, word search on a board, dictionary look-ups.
Checking a word letter by letter would repeat work across words.
The idea
O(length) per word or prefix time · O(total letters) spaceEach node has up to 26 children, one per next letter. Inserting a word walks (and creates) its path. Counting how many words pass through each node answers "how many start with this prefix?" by walking the prefix once.
Template · Insert, then walk a prefix
1def count_prefix(words, prefix):2 root = {}3 for word in words:4 node = root5 for ch in word:6 node = node.setdefault(ch, {})7 node['#'] = node.get('#', 0) + 1 # words through here8 node = root9 for ch in prefix:10 if ch not in node:11 return 012 node = node[ch]13 return node.get('#', 0) if prefix else len(words)
The template, filled in for Count words with a prefix. The highlighted lines are the part every problem of this kind shares.
The best, free
One of eachPractice set
Loading your mission…
Common mistakes
1Not marking where a word ends: "app" and "apple" share a path.
2Creating a new node for a letter that already exists, splitting shared paths.
3Using a trie when a hash set of whole words would do.
Check yourself
Question 1 of 2Checking whether a 5-letter prefix exists in a trie of 100,000 words takes about…