Insert, search and prefix
A trie stores words letter by letter in a tree, so words with a common beginning share a path. Inserting or looking up a word takes one step per letter, whatever the number of words, and 'does any word start with this?' is just a walk down the prefix.
How to recognise it
- Many words and questions about prefixes.
- Autocomplete: every word starting with what has been typed.
- The shortest prefix that tells one word apart from the others.
The structure page shows the trie on its own; this lesson is about using it.
The three operations
insert(w): node = root; for c in w: node = node.child[c] (create if missing); node.end = true
search(w): walk w; true if the walk finishes and node.end
prefix(p): walk p; true if the walk finishes
Counts on the nodes
Keep pass (words through the node) and end (words ending there) to answer "how many words equal w" and "how many
start with p", and to erase a word by decreasing both along its path.
| Problem | What the trie gives |
|---|---|
| implement a trie | insert, search, starts-with |
| counts and erase | pass and end counters |
| shortest unique prefix | the first node on a word's path with pass = 1 |
| phone directory | the subtree under each typed prefix, read in letter order |
| unique rows | a binary trie: a row that creates a new node was not seen before |
Common mistakes
- Treating a prefix as a stored word (forgetting
end). - Creating nodes during a search.
Problems
- Implement Trie (Prefix Tree)mediumguide ready
- Implement Trie II (Prefix Tree)mediumguide ready
- Find shortest unique prefix for every word in a given listmediumguide ready
- Implement a Phone Directorymediumguide ready
- Print unique rows in a given boolean matrixmediumguide ready