A tree of prefixes
Think of a paper dictionary’s thumb index: to find “card”, you open the C section, then look for “ca”, then “car”. Every word starting with “car” sits in the same place.
A trie works the same way. Each node represents a prefix, and its children are the possible next letters:
(root)
└─ c
└─ a
├─ r ← "car" ends here
│ ├─ d ← "card"
│ └─ e ← "care"
└─ t ← "cat"Two things to remember:
- Each node has a map from character → child node.
- A node has an isWord flag that says “a word ends here”. The path c → a → r exists for “card” too, but “car” is only a word if its last node is marked.
Inserting or looking up a word of length L walks L nodes: O(L), whether the trie holds ten words or ten million.
A trie (prefix tree) maps each key to a root-to-node path, one edge per symbol, with an end-of-key marker (or a stored value) on the final node. Insert, exact lookup and prefix lookup are O(L) in the key length, independent of the number of keys n, and prefix enumeration is O(L + output). Children are stored as a hash map (any alphabet, more overhead per node), a fixed array (26 for lowercase ASCII: fastest, memory-hungry and sparse), or a sorted array (compact, binary-searched). Space is O(total characters) in the worst case but shared prefixes compress it; radix (compressed) tries merge single-child chains to cut node count, and ternary search trees or DAWGs/FSTs are used when memory matters (Lucene’s term dictionary is an FST). Watch for Unicode: iterate grapheme clusters or code points consistently on insert and lookup.
final class Trie {
private final class Node {
var children: [Character: Node] = [:]
var isWord = false
}
private let root = Node()
func insert(_ word: String) {
var node = root
for ch in word {
if let next = node.children[ch] {
node = next
} else {
let next = Node()
node.children[ch] = next
node = next
}
}
node.isWord = true // mark where the word ends
}
func search(_ word: String) -> Bool { find(word)?.isWord ?? false }
func startsWith(_ prefix: String) -> Bool { find(prefix) != nil }
private func find(_ s: String) -> Node? {
var node = root
for ch in s {
guard let next = node.children[ch] else { return nil }
node = next
}
return node
}
}class Trie {
private class Node {
val children = HashMap<Char, Node>()
var isWord = false
}
private val root = Node()
fun insert(word: String) {
var node = root
for (ch in word) node = node.children.getOrPut(ch) { Node() }
node.isWord = true // mark where the word ends
}
fun search(word: String): Boolean = find(word)?.isWord == true
fun startsWith(prefix: String): Boolean = find(prefix) != null
private fun find(s: String): Node? {
var node = root
for (ch in s) node = node.children[ch] ?: return null
return node
}
}class Trie {
private static final class Node {
final Map<Character, Node> children = new HashMap<>();
boolean isWord;
}
private final Node root = new Node();
void insert(String word) {
Node node = root;
for (char ch : word.toCharArray()) {
node = node.children.computeIfAbsent(ch, c -> new Node());
}
node.isWord = true; // mark where the word ends
}
boolean search(String word) {
Node node = find(word);
return node != null && node.isWord;
}
boolean startsWith(String prefix) { return find(prefix) != null; }
private Node find(String s) {
Node node = root;
for (char ch : s.toCharArray()) {
node = node.children.get(ch);
if (node == null) return null;
}
return node;
}
}class TrieNode {
children = new Map<string, TrieNode>();
isWord = false;
}
class Trie {
private readonly root = new TrieNode();
insert(word: string): void {
let node = this.root;
for (const ch of word) {
let next = node.children.get(ch);
if (!next) {
next = new TrieNode();
node.children.set(ch, next);
}
node = next;
}
node.isWord = true; // mark where the word ends
}
search(word: string): boolean { return this.find(word)?.isWord ?? false; }
startsWith(prefix: string): boolean { return this.find(prefix) !== undefined; }
private find(s: string): TrieNode | undefined {
let node: TrieNode | undefined = this.root;
for (const ch of s) {
node = node.children.get(ch);
if (!node) return undefined;
}
return node;
}
}insertwalks the word letter by letter, creating a child when it’s missing, and marks the last node.findwalks a string and returns the node it ends on, or nothing if a letter is missing.searchneeds that node and itsisWordflag;startsWithonly needs the node to exist.
Predict the output
A trie contains car, card and care. What do search("ca"), startsWith("ca") and search("car") return?
The path c → a exists, so startsWith("ca") is true, but no word ends at the a node, so search("ca") is false. The r node was marked when car was inserted, so search("car") is true, even though card and care continue below it.
Tap the line with the bug.
func search(_ word: String) -> Bool {
return find(word) != nil
}fun search(word: String): Boolean {
return find(word) != null
}boolean search(String word) {
return find(word) != null;
}search(word: string): boolean {
return this.find(word) !== undefined;
}Hint: After inserting only apple, is app a word?
search returns true whenever the path exists, so after inserting “apple”, search("app"), search("a") and even search("") all return true. That’s startsWith, not search. A spell checker built on it would accept “appl” as a correct word.
A word exists only if its last node is marked:
func search(_ word: String) -> Bool { find(word)?.isWord ?? false }fun search(word: String): Boolean = find(word)?.isWord == trueboolean search(String word) {
Node node = find(word);
return node != null && node.isWord;
}search(word: string): boolean { return this.find(word)?.isWord ?? false; }Practice: Longest Common Prefix
Longest Common Prefix
Return the longest prefix shared by all strings in the array, or an empty string if there’s none.
["flower", "flow", "flight"] → "fl"
["dog", "racecar", "car"] → ""›
Insert every word into a trie. The common prefix is the path from the root while each node has exactly one child and no word ends there.
›
You can also solve it without a trie: compare characters of the first word with all the others, column by column. Try both and compare.
SolutionTry it yourself firstTime O(total characters)Space O(1) for the column scan
The column scan is shorter and uses no extra memory, so it’s the better answer here; the trie version shines when the same set of words is queried many times.
func longestCommonPrefix(_ words: [String]) -> String {
guard let first = words.first else { return "" }
let chars = words.map(Array.init)
for i in 0..<chars[0].count {
for word in chars.dropFirst() where i >= word.count || word[i] != chars[0][i] {
return String(chars[0][..<i])
}
}
return first
}fun longestCommonPrefix(words: Array<String>): String {
if (words.isEmpty()) return ""
val first = words[0]
for (i in first.indices) {
for (word in words) {
if (i >= word.length || word[i] != first[i]) return first.substring(0, i)
}
}
return first
}String longestCommonPrefix(String[] words) {
if (words.length == 0) return "";
String first = words[0];
for (int i = 0; i < first.length(); i++) {
for (String word : words) {
if (i >= word.length() || word.charAt(i) != first.charAt(i)) return first.substring(0, i);
}
}
return first;
}function longestCommonPrefix(words: string[]): string {
if (words.length === 0) return "";
const first = words[0];
for (let i = 0; i < first.length; i++) {
for (const word of words) {
if (i >= word.length || word[i] !== first[i]) return first.slice(0, i);
}
}
return first;
}Choosing the child representation
| Children as | Lookup | Memory | Use when |
|---|---|---|---|
| Hash map | O(1) average | Highest per node | Any alphabet, sparse nodes |
| Array of 26 | O(1), no hashing | 26 slots per node, mostly empty | Lowercase ASCII, interview speed |
| Sorted array | O(log k) | Compact | Large static dictionaries |
| Radix trie (merged chains) | O(L) | Far fewer nodes | Routers, IP lookups, long keys with shared prefixes |
Trie vs alternatives: a hash set answers exact lookups in O(L) with less memory but can’t enumerate prefixes; a sorted array with binary search finds the range of words with a prefix in O(L log n) and is far more cache-friendly, which often wins for static data. Tries win when there are many prefix queries on a changing set, or when the traversal itself is the algorithm (Word Search II, wildcard matching, longest-prefix match in routing tables).
- Trie: one edge per symbol, end marker on the last node. Insert, search, startsWith: O(L); enumerate a prefix: O(L + output). Space O(total characters), shared prefixes compress.
searchneeds the end marker; a path only proves a prefix.- Children: hash map (any alphabet), array of 26 (fast, sparse), sorted array (compact); radix tries merge single-child chains.
- Versus a hash set (exact only, smaller) and a sorted array (prefix range by binary search, cache-friendly): use a trie for many prefix queries on changing data, or when traversal drives the algorithm.
- Unicode: iterate the same unit (characters, code points) on insert and lookup.
Check this part
A trie holds a million words. How many nodes does looking up a 5-letter word visit?
The trie contains only apple. Is app found by search?
For a large static dictionary with prefix queries, what is often faster in practice than a pointer-based trie?
What does a radix (compressed) trie change?