Trie Operations
PremiumWords share their prefixes along one tree of letters.
O(L) time · O(N × L) spaceVisualizePrefix tree for efficient string search, autocomplete, and word dictionary problems.
1 algorithm3 problems
Words share their prefixes along one tree of letters.
O(L) time · O(N × L) spaceVisualizeA trie, also called a prefix tree, stores a set of words so that questions about how words begin are fast. It powers the suggestions under a search box, command palettes, contact pickers, code completion and spell checkers, and it routes network addresses by their longest matching prefix. In interviews it appears whenever a problem asks about prefixes across many words, such as autocomplete, word search on a board, or a shared start.
Each step down the tree is one letter, so words that begin the same way share one path from the root until they part. A node also carries a mark saying a whole word ends there, which is how the trie tells app apart from the first three letters of apple. Reaching a prefix costs one step per letter, however many words are stored, and everything below that node starts with that prefix.
Autocomplete and longest prefix build the same tree and read it in opposite directions: autocomplete goes from a prefix down to words, longest prefix goes from the words to the part they share. A trie is not always the best container. A hash map, covered in the Hash Map section, answers "is this exact word stored" with less memory but cannot list words by prefix. A sorted list searched with binary search, in the Searching section, also finds a prefix range and suits word lists that rarely change. To find a pattern inside a long text rather than among stored words, use KMP in the String Algorithms section. The usual trie bug is leaving out the word end mark, which makes app disappear as a word of its own.