Autocomplete
Engine
Type three characters and instantly see every word in a million-word dictionary that starts with them. A Trie makes this O(m) per query — where m is only the prefix length, not the dictionary size.
Why not a hash map?
A hash map gives O(1) exact-key lookup — but it cannot answer "give me all keys that start with X" without scanning every entry. A Trie stores characters as tree edges, so the prefix path leads directly to the subtree of all matching words.
Insert a word
Walk character by character. Create a child node if one does not exist. Mark the final node as an end-of-word. Time: O(m) — exactly one node per character.
1function insert(root, word):2 node = root3 for each char in word:4 if char not in node.children:5 node.children[char] = new TrieNode()6 node = node.children[char]7 node.isEndOfWord = true
Autocomplete query
First locate the prefix node in O(m), then DFS from that node to collect every word in the subtree.
1function autocomplete(root, prefix):2 node = root3 for each char in prefix:4 if char not in node.children:5 return [] // prefix not found6 node = node.children[char]7 // now DFS from prefix node to collect all words8 return dfsCollect(node, prefix)910function dfsCollect(node, current):11 results = []12 if node.isEndOfWord: results.append(current)13 for char, child in node.children:14 results += dfsCollect(child, current + char)15 return results
Query flow: typing “ca”
User types 'ca'
Walk the trie two hops: root → 'c' → 'a'. Reach the node representing the prefix 'ca'. Time cost: O(2) — one hop per character.
Time complexity
Linear time
Linear time
Constant time
Production enhancements
🎯 Quick Check
A trie holds 1,000,000 words. Querying for all words starting with 'pre' takes O(?) time.