Trie (Prefix Tree)
A trie (pronounced "try", from retrieval) is a tree where each node represents a character, and each path from root to a marked node spells out a word. All words that share a common prefix share the same path from the root.
Think of how a paper dictionary is organized: all words starting with "ca" are grouped together — "cat", "car", "card", "care". A trie makes this grouping explicit in the data structure itself.
Structure
Each trie node contains:
- An array (or map) of up to 26 child pointers — one per letter of the alphabet
- A boolean flag:
is_end_of_word— marks that a complete word ends here
The root represents the empty string — no character. Words are formed by following edges from parent to child, each edge labeled with a letter.
← → arrow keys to step · click elements to interact
Trie: Insert, Search & startsWith
Inserting a word
To insert "cat":
- Start at root. Does root have a child 'c'? If not, create one.
- Move to the 'c' node. Does it have child 'a'? If not, create one.
- Move to 'a' node. Does it have child 't'? If not, create one.
- Mark the 't' node as
is_end = True.
Inserting "car" after "cat": steps 1-2 are shared (the 'c'->'a' path already exists), then at 'a' we add a new child 'r' and mark it as end. The shared prefix uses the same nodes — no duplication!
Searching for a word
Follow the characters one by one. If any character is missing → word not in trie. If you reach the end of the word, check is_end.
Prefix search (autocomplete)
The killer feature: check if any word starts with a given prefix in \(O(L)\) time, where L is the prefix length. Walk the prefix; if successful, every word reachable from that node is a valid completion.
When to use a trie
- Autocomplete — search bars, IDE suggestions, spell checkers
- Spell checking — store dictionary, check word existence in \(O(L)\)
- IP routing tables — longest prefix matching
- Word games — find all words with a given prefix instantly
Space consideration
Each node may store up to 26 child pointers (for lowercase English). For sparse character sets, a hash map is preferred over an array. The total space is \(O(total characters across all inserted words)\).
Complexity
Count Words With Prefix
Quick check
Continue reading