Chapter 11: Tries
Introduction
Learning Outcomes
Explain how a trie is built from a root, nodes, edges and end-of-word marks; draw the trie of a set of words.
Implement insert, search, prefix query, autocomplete and delete in Java and trace them step by step.
Justify the O(L) time and O(N · M) memory of the operations; compare tries with hash tables and BSTs.
Explain which problem compressed tries, suffix tries and Aho–Corasick each solve.
Trie Basics
The Trie (Prefix Tree)
- A tree-like data structure that stores strings for fast lookup.
- The root is empty; each step down from the root represents one character.
- Words are stored as paths from the root; common prefixes are stored only once.
- Applications: autocomplete, spell checking, IP routing.
Trie Basics
Why a Trie?
We want every word in a dictionary that starts with "an". How do different structures answer this?
Trie Basics
Basic Components
isEnd: a word ends at this node.The colored node represents the prefix "an"; "an" is not a word (unmarked), but it is a prefix of "and" and "ant".
Trie Basics
Example: A Seven-Word Trie
| Words |
|---|
| ab · aba · abc |
| ad |
| ba · bad · bag |
7 words, 18 characters in total → only 9 nodes (+ root).
isEnd mark is essential.Trie Basics
Example: A Trie with Values
| Key | Value | Key | Value |
|---|---|---|---|
| A | 15 | tea | 3 |
| i | 11 | ted | 4 |
| in | 5 | ten | 12 |
| inn | 9 | to | 7 |
isEnd. "t" and "te" carry no value; they are only prefixes. The uppercase "A" needs a wider alphabet (e.g. a HashMap) than a 26-letter array.Implementation
The Trie Node Class
public class TrieNode { TrieNode[] children; // 'a'..'z' boolean isEnd; // word ends here? public TrieNode() { isEnd = false; children = new TrieNode[26]; } }
- Each node holds 26 child references, all
nullinitially. - The character is not stored in the node: it is implied by which index of the parent the node sits at.
isEnd: is the path from the root to here a word?
The root's children array after inserting and, ant, dad, do: only 2 of the 26 cells are used (⁄ = null).
Implementation
From Character to Index: ch − 'a'
| ch | Unicode | ch − 'a' |
|---|---|---|
| 'a' | 97 | 0 |
| 'd' | 100 | 3 |
| 'n' | 110 | 13 |
| 'o' | 111 | 14 |
| 't' | 116 | 19 |
| 'z' | 122 | 25 |
- In Java a
charis a number;ch - 'a'maps a lowercase letter to 0..25. - Accessing a child by array index is O(1):
node.children[ch - 'a']. - For "and",
children[0],children[13],children[3]are used in turn.
'A' - 'a' = −32, 'ç' - 'a' = 134 → ArrayIndexOutOfBoundsException. For uppercase or Turkish letters, normalize the input or use a HashMap.Insertion
Insertion
public void insert(String word) { TrieNode node = root; for (char ch : word.toCharArray()) { int i = ch - 'a'; if (node.children[i] == null) node.children[i] = new TrieNode(); node = node.children[i]; } node.isEnd = true; }
- Start at the root.
- For each character of the word, look at the matching child:
children[ch − 'a']. - If the child is
null, create a new node; otherwise (a shared prefix) reuse the existing node. - Move to that child.
- When the characters run out, set
isEnd = trueon the last node.
Insertion · Step by step
Insertion Step by Step: and, ant, dad, do
Initially the trie is just the root; all 26 of its children are null and isEnd = false.
Inserting "and", character 'a': children[0] null → create a new node and move to it.
Inserting "and", character 'n': children[13] null → create a new node and move to it.
Inserting "and", character 'd': children[3] null → create a new node and move to it.
Characters exhausted: isEnd = true on the last node (double circle). "and" inserted. The path children[0] → children[13] → children[3] from the root is in place.
Inserting "ant", character 'a': children[0] is set → move to the existing "a" node (shared prefix).
Inserting "ant", character 'n': children[13] is set → move to the existing "an" node (shared prefix).
Inserting "ant", character 't': children[19] null → create a new node and move to it.
Characters exhausted: isEnd = true on the last node (double circle). "ant" inserted. Only 1 new node was needed: the prefix "an" is shared.
Inserting "dad", character 'd': children[3] null → create a new node and move to it.
Inserting "dad", character 'a': children[0] null → create a new node and move to it.
Inserting "dad", character 'd': children[3] null → create a new node and move to it.
Characters exhausted: isEnd = true on the last node (double circle). "dad" inserted.
Inserting "do", character 'd': children[3] is set → move to the existing "d" node (shared prefix).
Inserting "do", character 'o': children[14] null → create a new node and move to it.
Characters exhausted: isEnd = true on the last node (double circle). "do" inserted. Final state: 4 words, 11 characters, 8 nodes excluding the root.
Insertion · Step through the code
insert("ant"): Step Through the Code
The trie holds only "and". node starts at the root.
Character 'a' → i = 'a' − 'a' = 0.
node.children[0] is not null → no new node needed.
node is now the "a" node.
Character 'n' → i = 'n' − 'a' = 13.
node.children[13] is not null → no new node needed.
node is now the "an" node.
Character 't' → i = 't' − 'a' = 19.
node.children[19] == null → condition true.
A new TrieNode is created and linked at children[19] (isEnd = false).
node is now the "ant" node.
Loop done: node.isEnd = true. "ant" inserted; only 1 node was created.
public void insert(String word) { TrieNode node = root; for (char ch : word.toCharArray()) { int i = ch - 'a'; if (node.children[i] == null) node.children[i] = new TrieNode(); node = node.children[i]; } node.isEnd = true; }
Search
Search
public boolean search(String word) { TrieNode node = root; for (char ch : word.toCharArray()) { int i = ch - 'a'; if (node.children[i] == null) return false; node = node.children[i]; } return node.isEnd; }
- Start at the root.
- For each character, follow the matching branch (child).
- If the branch is missing (
null), the word is not in the trie.
- If the branch is missing (
- At the end of the word, check
isEnd:true→ the word is found;false→ not a word; it is only a prefix of a stored word.
Search · Step through the code
search("dad"): Step Through the Code
Trie: and, ant, dad, do. node starts at the root.
Character 'd' → i = 3.
children[3] is not null → branch exists, continue.
node = "d".
Character 'a' → i = 0.
children[0] is not null → branch exists, continue.
node = "da".
Character 'd' → i = 3.
children[3] is not null → branch exists, continue.
node = "dad".
End of word; node.isEnd = true → return true (word found).
public boolean search(String word) { TrieNode node = root; for (char ch : word.toCharArray()) { int i = ch - 'a'; if (node.children[i] == null) return false; node = node.children[i]; } return node.isEnd; }
Search
Three Possible Outcomes of a Search
isEnd = false: "da" is only a prefix.children[6] ('g') is null: no branch, early exit.Dashed red circle: a node that was searched for but is not in the trie.
Search
Prefix Query: startsWith
public boolean startsWith(String prefix) { TrieNode node = root; for (char ch : prefix.toCharArray()) { int i = ch - 'a'; if (node.children[i] == null) return false; node = node.children[i]; } return true; // search: node.isEnd }
| Query | search | startsWith |
|---|---|---|
| "dad" | true | true |
| "da" | false | true |
| "an" | false | true |
| "dog" | false | false |
Search · Step through the code
startsWith("da") and startsWith("dog")
The trie holds and, ant, dad, do (ringed node = word end). First startsWith("da"): node is set to the root.
ch = 'd', i = 3: children[3] is set → node moves down to that child ("d").
ch = 'a', i = 0: children[0] is set → node moves down to that child ("da").
The prefix is consumed and the path never broke → true. Node "da" is unmarked, so search("da") would return false; a prefix query ignores the end mark.
Second call startsWith("dog"): node is reset to the root.
ch = 'd', i = 3: children[3] is set → node moves down to that child ("d").
ch = 'o', i = 14: children[14] is set → node moves down to that child ("do").
ch = 'g', i = 6: children[6] of node "do" is null → false. "do" is a word, but no word starts with "dog".
public boolean startsWith(String prefix) { TrieNode node = root; for (char ch : prefix.toCharArray()) { int i = ch - 'a'; if (node.children[i] == null) return false; node = node.children[i]; } return true; // search: node.isEnd }
Search
Prefix Counter: countPrefix in O(P)
void insert(String word) { if (search(word)) return; TrieNode d = root; d.count++; for (char ch : word.toCharArray()) { int i = ch - 'a'; if (d.children[i] == null) d.children[i] = new TrieNode(); d = d.children[i]; d.count++; // one more word passed } d.isEnd = true; } int countPrefix(String prefix) { TrieNode d = root; for (char ch : prefix.toCharArray()) { d = d.children[ch - 'a']; if (d == null) return 0; } return d.count; }
| Query | result |
|---|---|
| countPrefix("an") | 2 |
| countPrefix("da") | 1 |
| countPrefix("x") | 0 |
int count per node; without it the query walks the subtree, O(P + S · M).Search
Wildcard Search: "d.d"
boolean wildcard(TrieNode d, String s, int j) { if (d == null) return false; if (j == s.length()) return d.isEnd; char ch = s.charAt(j); if (ch != '.') return wildcard(d.children[ch - 'a'], s, j + 1); for (int i = 0; i < 26; i++) if (wildcard(d.children[i], s, j + 1)) return true; return false; }
| Pattern | result | match |
|---|---|---|
| "d.d" | true | dad |
| ".n." | true | and |
| ".o" | true | do |
| "b.." | false | no b branch |
| "...." | false | no 4-letter word |
- Trie: and, ant, dad, do. Call
wildcard(root, pattern, 0). - A normal letter narrows the search to one path; '.' tries every non-null branch (backtracking). The first match propagates
trueupward. - Worst case 26k branches for k wildcards, but empty branches return at once: the real cost is bounded by the paths that exist in the trie. A hash table can answer this only by scanning every word.
Search
Spell Checking: Edit Distance on a Trie
- Question: which dictionary words are within edit distance (insert / delete / replace) at most 1 of "dod"?
- Instead of computing the distance to each word separately, traverse the trie depth-first; each node derives one DP row from its parent's row.
- A common prefix's row is computed once: the "d" row serves both dad and do.
- Pruning: if the row's minimum exceeds k, no word in the subtree can be within k; the minimum of row "an" is 2 > 1, so and and ant are never visited.
| node | "" d o d | last | action |
|---|---|---|---|
| a | 1 1 2 3 | — | continue |
| an | 2 2 2 3 | — | prune (min 2) |
| d | 1 0 1 2 | — | continue |
| da | 2 1 1 2 | — | continue |
| dad | 3 2 2 1 | 1 | suggest |
| do | 2 1 0 1 | 1 | suggest |
The last cell of a row is the distance between the node's word and "dod".
Search · Step through the code
Autocomplete: complete("te")
First findNode("te") walks t → e from the root to node "te" (like a prefix query).
Starting at node "te", the subtree is traversed depth-first.
"te" is not a word (isEnd = false) → not added to the list.
i = 0: children[0] ('a') is set → path = "tea".
Recursive call: collect("tea").
"tea" is marked → added to result. No children; the loop passes over 26 empty indices.
The call returns; drop the last letter (path = "te") → backtracking.
i = 3: children[3] ('d') is set → path = "ted".
Recursive call: collect("ted").
"ted" is marked → added to result. No children; the loop passes over 26 empty indices.
The call returns; drop the last letter (path = "te") → backtracking.
i = 13: children[13] ('n') is set → path = "ten".
Recursive call: collect("ten").
"ten" is marked → added to result. No children; the loop passes over 26 empty indices.
The call returns; drop the last letter (path = "te") → backtracking.
Loop done; complete("te") → [tea, ted, ten]. Thanks to index order (a < d < n), the results come out in alphabetical order.
List<String> complete(String prefix) {
List<String> result = new ArrayList<>();
TrieNode d = findNode(prefix);
if (d != null)
collect(d, new StringBuilder(prefix), result);
return result;
}
void collect(TrieNode d, StringBuilder path,
List<String> result) {
if (d.isEnd) result.add(path.toString());
for (int i = 0; i < 26; i++)
if (d.children[i] != null) {
path.append((char) ('a' + i));
collect(d.children[i], path, result);
path.setLength(path.length() - 1);
}
}Search · Step through the code
longestCommonPrefix(): Code Trace
Trie: kar, kart, karton. Walk down from the root through nodes that have one child and are unmarked.
The root is unmarked; count its children: only 'k' is set → count = 1, only = 10.
Append 'k', d = "k". This node also has a single child ('a', only = 0).
Append 'a', d = "ka"; its single child is 'r' (only = 17).
Append 'r', d = "kar". "kar" is a word → the loop ends: even with a single child, the word "kar" does not share a longer prefix.
Returns "kar". With only kart and karton in the trie, the walk would continue to "kart" and stop at its end mark: "kart".
String longestCommonPrefix() {
StringBuilder sb = new StringBuilder();
TrieNode d = root;
while (!d.isEnd) {
int only = -1, count = 0;
for (int i = 0; i < 26; i++)
if (d.children[i] != null) { count++; only = i; }
if (count != 1) break; // branch or leaf
sb.append((char) ('a' + only));
d = d.children[only];
}
return sb.toString();
}Search
Try It: Trie Operations
Lowercase a–z only (at most 10 letters, 14 words). Double circle: word end · orange: last visited node · dashed red: missing branch. Enter = insert.
Deletion
Deletion: Three Cases
isEnd = false; no node is removed.Show answer
Only the isEnd mark of the last 'p' node is cleared. The node cannot be removed, because "apple" continues below it (case 1).
Deletion · Step by step
Deletion Step by Step: app, apple, apt
Start: app, apple, apt (6 nodes excluding the root). Both scenarios below start from this trie.
delete("app"): follow a → p → p; node "app" is marked, so the word exists.
isEnd = false. The node has a child ('l'), so it is not removed → case 1. "apple" is still found.
delete("apple") (again from the original trie): follow a-p-p-l-e; "apple" is found.
Node 'e' loses its mark; it has no children → its parent removes it (children[4] = null).
Node 'l' is now childless and unmarked → it is removed too.
Node "app" is marked (another word) → deletion stops here. Result: app, apt; 4 nodes excluding the root (case 2).
Deletion
Deletion: Recursive Code
// true: the parent may remove d boolean delete(TrieNode d, String k, int j) { if (j == k.length()) { // end of word if (!d.isEnd) return false; d.isEnd = false; return isEmpty(d); // childless? } int i = k.charAt(j) - 'a'; TrieNode c = d.children[i]; if (c == null) return false; // no such word if (delete(c, k, j + 1)) { d.children[i] = null; // remove the child return !d.isEnd && isEmpty(d); } return false; }
- Call:
delete(root, word, 0); the root's return value is ignored. - First descend to the end of the word; removal decisions are made on the way back (bottom-up).
- A node is removed only if it has no children and is unmarked.
isEmpty(d): are all 26 children null? (O(M)).- Time: O(L · M) with an array; O(L) if a child count is kept.
- In the counting version, if the word exists (check with
searchfirst), dod.count--at each node on the way down.
Deletion · Step through the code
delete(root, "dad", 0)
delete(root, "dad", 0): the first character is 'd' → i = 3, c = the root's 'd' child. Removal decisions come on the way back; first we descend.
delete(d, "dad", 1): 'a' → i = 0, c = node "da". The recursive call goes one level deeper.
delete(da, "dad", 2): 'd' → i = 3, c = node "dad".
j = 3 = k.length(): end of word. "dad" is marked, so set isEnd = false.
isEmpty(dad) = true: the node has no children → return true; the parent may remove it.
delete(da) returned true → d.children[3] = null: node "dad" is cut off.
"da" is unmarked and now childless → true: this node can be removed too.
delete(d) returned true → d.children[0] = null: node "da" is cut off.
"d" is unmarked but has the child 'o' for "do" → isEmpty is false → false. Deletion stops here.
At the root, delete(d) returned false → the root removes nothing and returns false (the value is ignored). Remaining words: and, ant, do.
// true: the parent may remove d boolean delete(TrieNode d, String k, int j) { if (j == k.length()) { // done if (!d.isEnd) return false; d.isEnd = false; return isEmpty(d); // childless? } int i = k.charAt(j) - 'a'; TrieNode c = d.children[i]; if (c == null) return false; if (delete(c, k, j + 1)) { d.children[i] = null; // remove child return !d.isEnd && isEmpty(d); } return false; }
Analysis
Complexity
| Operation | Time | Notes |
|---|---|---|
| insert(word) | O(L) | One step per character; at most L new nodes |
| search(word) | O(L) | Ends earlier if a branch is missing |
| startsWith(prefix) | O(P) | P: prefix length |
| complete(prefix) | O(P + S · M) | S: number of nodes in the subtree of the prefix node |
| delete(word) | O(L · M) | isEmpty scans 26 cells; O(L) with a child count |
Analysis
Memory: A Worked Example
Trie: and, ant, dad, do
| Total characters | 3 + 3 + 3 + 2 = 11 |
| Number of nodes N | 1 (root) + 8 = 9 |
| Child references | 9 × 26 = 234 |
| Used references | 8 (number of edges) |
| Empty (null) references | 226 (≈ 97%) |
Analysis
Pros and Cons
Pros
- Fast prefix-based search: autocomplete.
- Word lookup in O(L) time (L: word length).
- Overlapping prefixes are stored once: shared memory.
- Traversal yields words in lexicographic order; no hash collisions.
Cons
- High memory use, especially with large alphabets.
- Space complexity O(N · M) (N: number of nodes, M: alphabet size).
- No gain for sets with few common prefixes (e.g. random keys).
- Many small objects: not cache-friendly.
Analysis
Ways to Store the Children
| Representation | Child access | Memory per node | Notes |
|---|---|---|---|
TrieNode[26] array | O(1) | M references | Simple, fast; wasteful for sparse nodes |
HashMap<Character, TrieNode> | O(1) avg. | one per child | Works with any alphabet (Turkish, Unicode); no ordering |
TreeMap / sorted list | O(log M) | one per child | Keeps alphabetical traversal |
| Ternary search trie (TST) | O(log M) avg. | 3 references | Less / equal / greater link at each node |
node.children[i] becomes a call such as node.children.get(ch). Choose by alphabet size, memory and the need for ordered output.Analysis
Trie, Hash Table or BST?
| Operation (n words, length L) | Trie | Hash table | Balanced BST |
|---|---|---|---|
| Exact word lookup | O(L) | O(L) average | O(L · log n) |
| Prefix query | O(P) | not supported | O(P · log n) |
| k words with a prefix | O(P + S · M) | scan the whole table | O(P · log n + k · L) |
| Sorted listing | DFS, O(N · M) | needs sorting | inorder, O(n) |
| Worst case | O(L) | O(n · L) (collisions) | O(L · log n) |
| Memory | high | low | low |
A hash table also reads all L characters to compute the key's hash, so for exact lookup the two are of the same order. The trie's edge is in prefix and ordered queries. S: number of nodes in the subtree of the prefix node.
Analysis
Lexicographic Order with a Trie: Sorting Strings
- Input order: dog, ant, do, and, dad. Insert them all into a trie.
- Traverse the trie in preorder from the root, visiting children in 'a' → 'z' order and emitting a word at each marked node.
- Output: and, ant, dad, do, dog. A node is emitted before its children, so a prefix comes before its extensions (do < dog).
- With N total characters and a fixed alphabet, insertion is O(N) and traversal O(N·M) (M = 26 child checks): no need for the O(n log n) comparisons of a comparison sort, each costing O(L).
- The same idea underlies burst sort and string versions of MSD radix sort.
Applications and Variants
Applications
Applications and Variants · Step through the code
longestMatch(): Routing with a Binary Trie
Binary trie (alphabet {0, 1}); some nodes carry a route. addr = "0110": d = root, best = null.
k = 0: no route at the root. Bit '0' → d = "0".
k = 1: node "0" has A → best = A. Bit '1' → d = "01".
k = 2: "01" has B → best = B (the longer prefix wins). d = "011".
k = 3: "011" has C → best = C. No '0' branch → d = null, return C.
New address "1001": k = 0, no route at the root; d = "1".
k = 1: "1" has D → best = D. No '0' branch → return D. Without a more specific route, the general one applies.
"1101": descend 1 → 11 → 110. "11" is an internal node (no route), so best stays D.
k = 3: "110" has E → best = E; no '1' branch → E. The number of steps is bounded by the address length.
String longestMatch(String addr) {
BitNode d = root;
String best = null;
for (int k = 0; k < addr.length(); k++) {
if (d.route != null) best = d.route; // longer prefix
d = d.children[addr.charAt(k) - '0'];
if (d == null) return best;
}
return d.route != null ? d.route : best;
}Applications and Variants
The Maximum XOR Pair with a Binary Trie
- Question: which pair in [3, 10, 5, 25, 2, 8] maximizes a ⊕ b? Brute force tries n² pairs.
- Insert the numbers into a 5-bit binary trie, starting from the most significant bit.
- For each x, descend from the root and at every bit take the opposite branch if it exists: that bit of the result becomes 1. A 1 in a higher bit outweighs all lower bits combined, so the greedy choice is correct.
- For x = 5 = 00101 we want 11010: 1 ✓ (25), 1 ✓, 0 ✓, no 1 → 0, no 0 → 1: we reach 11001 = 25, 5 ⊕ 25 = 28.
| Method | time | n = 10⁵, B = 30 |
|---|---|---|
| All pairs | O(n²) | ≈ 5·10⁹ operations |
| Binary trie | O(n·B) | ≈ 6·10⁶ steps |
Applications and Variants
Ternary Search Tries
- Each node holds one character and three links:
left(smaller),mid(equal, go to the next character),right(larger). - A node's left/right chain is a small binary search tree over the “sibling” children of a trie.
- Word ends are marked in the node (ring). Insertion order shapes the tree: the first word inserted becomes the “spine”.
| kar, kal, at, ve, kas | nodes | links |
|---|---|---|
| Trie with 26-element arrays | 10 | 10 × 26 = 260 |
| TST | 9 | 9 × 3 = 27 |
Applications and Variants · Step through the code
TST: search("kas") and search("al")
TST: kar, kal, at, ve, kas. search("kas"): d = root ('k'), i = 0.
ch = 'k' = d.c and not the last character → mid link, i = 1. d = 'a'.
ch = 'a' equal → mid, i = 2. d = 'r'.
ch = 's' > 'r' → right link; i is unchanged (same character, searching the siblings). d = 's'.
ch = 's' equal and i = 2 is the last index → return d.end: true. 4 nodes visited for 3 characters.
search("al"): ch = 'a' < 'k' → left, d = 'a' (the branch of the word at).
'a' equal, not the last character → mid, i = 1, d = 't'.
'l' < 't' → left: null, false.
boolean search(String s) { TstNode d = root; int i = 0; while (d != null) { char ch = s.charAt(i); if (ch < d.c) d = d.left; else if (ch > d.c) d = d.right; else if (i == s.length() - 1) return d.end; else { d = d.mid; i++; } } return false; }
Applications and Variants
Compressed Tries (Radix / Patricia)
- Chains of single-child, unmarked nodes are merged into one edge, which now carries a substring ("an", "ad").
- Every internal node has at least 2 children (or an end-of-word mark), so the number of nodes is O(n) (n: number of words).
- Patricia (Morrison, 1968) is the binary-alphabet version of this idea; it is used in IP routing tables.
Applications and Variants
Suffix Tries
Insert every suffix of the text T = "abab" into a trie:
abab · bab · ab · b
- P is a substring of T ⇔ P is a prefix of some suffix ⇔ P is a path from the root.
- Query:
startsWith(P)→ O(m) (m = |P|), independent of the text length. E.g. "ba" is present, "bb" is not. - The price: up to O(n²) nodes for a text of length n.
- Suffix tree = compressed suffix trie: O(n) nodes, built in O(n) time by Ukkonen's algorithm.
Applications and Variants · Step through the code
suffixTrie("abab")
t = "abab": its 4 suffixes (abab, bab, ab, b) will be inserted in turn. The trie is just the root.
s = 0: start inserting suffix "abab"; d = root. s = 0, j = 0: 'a' branch missing → new node, d moves there ("a").
s = 0, j = 1: 'b' branch missing → new node, d moves there ("ab").
s = 0, j = 2: 'a' branch missing → new node, d moves there ("aba").
s = 0, j = 3: 'b' branch missing → new node, d moves there ("abab").
Suffix "abab" done → mark the last node (ring).
s = 1: start inserting suffix "bab"; d = root. s = 1, j = 1: 'b' branch missing → new node, d moves there ("b").
s = 1, j = 2: 'a' branch missing → new node, d moves there ("ba").
s = 1, j = 3: 'b' branch missing → new node, d moves there ("bab").
Suffix "bab" done → mark the last node (ring).
s = 2: the path "ab" already exists from inserting abab; descend without creating nodes and mark "ab".
s = 3: the path "b" exists too; only the mark is added. Shared prefixes are stored once: 8 nodes including the root.
The suffix trie is ready. "ba" is a path from the root → a substring; there is no path "bb" → not a substring. Query O(m).
TrieNode suffixTrie(String t) {
TrieNode root = new TrieNode();
for (int s = 0; s < t.length(); s++) {
TrieNode d = root;
for (int j = s; j < t.length(); j++) {
int i = t.charAt(j) - 'a';
if (d.children[i] == null)
d.children[i] = new TrieNode();
d = d.children[i];
}
d.isEnd = true; // suffix done
}
return root;
}Applications and Variants
Aho–Corasick: Many Patterns in One Pass
- The patterns (he, she, his, hers) go into a trie; the text is read once, left to right.
- Failure link (dashed): the longest proper suffix of the node's string that is in the trie. "she" → "he", "sh" → "h", "hers" → "s".
- When a branch is missing, fall back along the failure link; this is the multi-pattern counterpart of KMP's prefix table.
- Output sets merge along the failure chain: the "she" node also reports he.
| Text "ushers" | state | found |
|---|---|---|
| u, s, h | root, s, sh | — |
| e (index 3) | she | she, he |
| r | she → he → her | — |
| s (index 5) | hers | hers |
Time O(n + m + z): n text length, m total pattern length, z number of matches (Aho and Corasick, 1975). Used in virus signature scanning and banned-word filters.
Applications and Variants
Which Trie for Which Question?
| Structure | Stores | Good at | Query |
|---|---|---|---|
| Standard trie | a set of words | exact word, prefix, autocomplete | O(L) |
| Trie with prefix counts | + words through each node | “how many words have this prefix?” | O(P) |
| Compressed trie | single-child chains merged | long shared prefixes, memory | O(L) |
| Ternary search trie | 3 links per node | large alphabets, little memory | O(L + log n) avg. |
| Binary trie | bit strings (IP, integers) | longest prefix match, maximum XOR | O(B) |
| Suffix trie / array | all suffixes (array: O(n) memory) | “is P a substring of T?” | O(m) / O(m log n) |
| Aho–Corasick | pattern trie + failure links | many patterns in one pass | O(n + z) |
Summary
Summary
| Topic | Key points |
|---|---|
| Structure | empty root; each edge one character; a word = a path from the root; common prefixes are shared |
| Node | TrieNode[26] children + boolean isEnd; index = ch − 'a' |
| Insert | create a node if missing, else move on; mark the end — O(L) |
| Search | false if a branch is missing; return isEnd at the end — O(L) |
| Prefix | same path, no mark check — O(P); complete = DFS from the prefix node |
| Delete | clear the mark; remove childless, unmarked nodes bottom-up |
| Memory | O(N · M); HashMap / TST / compressed trie for sparse nodes |
| Variants | radix/Patricia trie, suffix trie → suffix tree, suffix array |
Summary
Common Mistakes
isEndChecking only that the path exists counts every prefix as a word: "da" appears to be found.'A' − 'a' = −32, 'ş' − 'a' = 254: out of array bounds. Lowercase the input or use a HashMap.Summary
Sample Problems
Insert the words in order: car, cart, care, cat, dog (trie with 26-element arrays).
- Draw the trie. How many nodes, including the root?
- What do
search("ca")andstartsWith("ca")return? - Write the result of
complete("car")in order. - How many nodes do
delete("car")and (from the original trie)delete("cart")remove? - How many child references are
nullin total? - How many nodes, including the root, does the compressed trie of the same five words have?
Show answers
- c-a-r(•)-t(•), car-e(•), ca-t(•); d-o-g(•) → 9 nodes excluding the root, 10 including it (17 characters).
search("ca")= false ("ca" is unmarked);startsWith("ca")= true.- [car, care, cart] — DFS emits a node before its children, which come in index order ('e' < 't').
delete("car"): 0 nodes (only the mark is cleared);delete("cart"): 1 node ('t'), stopping because "car" is marked.- 10 × 26 = 260 references, 9 of them used (the edges) → 251 null.
- 7: root, "ca", r(•), t(•) (cart), e(•) (care), t(•) (cat), "dog"(•); the chains c–a and d–o–g collapse into single nodes.
Summary
Exercises
int countWords(TrieNode d): count the trie's words.int countPrefix(String prefix): return the number of words with this prefix in O(P).String longestCommonPrefix(): find the longest common prefix of all words in the trie.- Write a trie with
HashMap<Character, TrieNode>children for Turkish letters. - How many nodes, with root, does the trie of A, to, tea, ted, ten, i, in, inn have?
- Search "abab"'s suffix trie for "bab" and "bb"; how many comparisons?
Answers / hints
- DFS:
(d.isEnd ? 1 : 0)+ the sum ofcountWordsover all non-null children. O(N · M). - An
int countper node, incremented byinserton its path; the prefix node's count is the answer. - From the root, descend while there is one child and
isEndis false; the characters passed are the answer. children.get(ch)/children.computeIfAbsent(ch, x -> new TrieNode()); no index arithmetic.- A, t, to, te, tea, ted, ten, i, in, inn = 10 nodes + root = 11.
- "bab": path b → a → b exists (3 steps). "bb": no 'b' after b → not found (2 steps).
Summary
References
- Sedgewick and Wayne, Algorithms, 4th ed., 2011 (Section 5.2: Tries).
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed., 2022.
- E. Fredkin, "Trie Memory", Communications of the ACM 3(9), 1960.
- D. R. Morrison, "PATRICIA — Practical Algorithm To Retrieve Information Coded in Alphanumeric", Journal of the ACM 15(4), 1968.
- U. Manber and G. Myers, "Suffix Arrays: A New Method for On-Line String Searches", SIAM Journal on Computing 22(5), 1993.
- D. Gusfield, Algorithms on Strings, Trees, and Sequences, Cambridge University Press, 1997.