Loading...
Tier II · Intermediate
Prefix trees for fast string lookup and shared-prefix problems.
A trie stores a set of sequences as one tree where every edge carries a symbol and every path from the root spells a prefix. Words that begin the same way share nodes, so a lookup costs the length of the word, not the size of the set.
| Node holds | C++ | Python | Java |
|---|---|---|---|
| Fixed alphabet | array<int, 26> | list of 26 | TrieNode[] |
| Sparse alphabet | unordered_map | dict | HashMap |
| Word ends here | bool | bool | boolean |
No standard library ships a trie, so the node is the whole design. A fixed array per node is fastest on 26 letters or 2 bits, a map per node when the alphabet is wide or sparse. Keep the end-of-word flag separate, because a stored word is also a prefix of longer ones and a trie without the flag quietly accepts strings nobody inserted. The alphabet need not be letters — feed it the bits of an integer, most significant first, and a walk preferring the opposite bit at every level maximises an XOR.
| Operation | Trie | Hash set |
|---|---|---|
| Insert or find a word of length | ||
| Every word under a prefix | ||
| Memory | one node per distinct prefix | one entry per word |
Use one when the question is about prefixes rather than whole words — the shortest stored prefix of a query, a word built a letter at a time from other words, or the best XOR partner, the same question over bits.
The problems below start with the shared-prefix idea on its own and two character tries, then switch substrate to Binary Tries for the maximum XOR pair and the same walk under a limit.
Recommended first: Hash Maps, Depth-First Search I.
You've cleared 0 of 12 problems in these. You can dive in anyway.