Tries
A tree that stores strings one character per level, so words that share a prefix share a path. Prefix lookups cost O(length of the key), however many words are stored.
Overview
A trie (also called a prefix tree) stores a set of strings as paths in a tree. Each edge is one character. Each node stands for the prefix spelled on the way down from the root, and a flag on the node says whether that prefix is also a complete word. Edward Fredkin took the name from the middle of the word retrieval.
Tries fit when a problem asks many questions about prefixes: autocomplete, 'does any word start with this?', replacing words with their shortest root, or searching a grid for many words at once. A hash set answers 'is this exact word stored?' just as fast, but it cannot answer 'which words start with this?' without scanning everything. This chapter builds one small trie, runs every operation on it, and then turns the same idea to grids, compressed edges and the bits of numbers.
Each section below follows the same shape: the rule first, then the rule on a small example, then the trap to avoid.
The shape of a trie
The rule: words that share a prefix share the nodes for it, and a node can be a word end and still have children.
The words car, card, care and cat share the prefix ca, so they share the first two nodes. car is a word, and card continues below it.
Each node holds two things: a map from character to child, and a boolean is_word. Some problems add more, such as a counter, the full word, or the best suggestions for that prefix.
Sign up free to read the full topic
More Coding & DSA topics
Start free on Cariara · Coding problems · System design studio