Project · Trie

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.

root
/ \
c d
/ \
a o
/ \ \
t r* g*
* / \
t* *
* = isEndOfWord | words: cat, car, cart, car, dog

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.

trie-insert
1function insert(root, word):
2 node = root
3 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.

autocomplete + dfs-collect
1function autocomplete(root, prefix):
2 node = root
3 for each char in prefix:
4 if char not in node.children:
5 return [] // prefix not found
6 node = node.children[char]
7 // now DFS from prefix node to collect all words
8 return dfsCollect(node, prefix)
9 
10function 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”

1 / 3
1

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.

1 of 3

Time complexity

Insert one word — O(m) where m = word lengthO(n)

Linear time

Autocomplete query — O(m + k) where m = prefix, k = result charsO(n)

Linear time

Space per node — 26 child pointers + isEndOfWord flagO(1)

Constant time

Production enhancements

Ranked results
Store a frequency counter at each end-of-word node. Sort DFS results by count descending.
Fuzzy matching
Allow one edit-distance error by branching during prefix walk when a character mismatches.
Compressed trie
Merge single-child chains into one edge (Patricia / Radix trie). Reduces node count by up to 50%.
🔍Why DFS not BFS for collection?
DFS uses stack space proportional to the word length. BFS would require a queue holding all nodes at each level — much larger. DFS is also naturally recursive and produces results in depth-first (alphabetical) order when children are stored sorted.

🎯 Quick Check

A trie holds 1,000,000 words. Querying for all words starting with 'pre' takes O(?) time.