Tries & union-find
Use tries for prefixes and union-find for connectivity.
By Invicly Tech, , in Interview Preparation. About 13 minutes to read.
In short
A trie stores words character by character so all words sharing a prefix share a path. Union-find tracks which items are connected, merging groups in nearly constant time.
Explained simply
A trie (said like "try") is a tree for storing words, one letter per step. Think of a phone contact list: type "ma" and it shows Mark, Maria and Max. Those names share the path m, a, and only split after that. A trie stores that shared start once, so finding every word with a given prefix is quick.
Each node in a trie holds its children (one for each next letter) and a small flag that says "a word ends here". Without that flag you could not tell that "car" is a word but "ca" is not.
Union-find solves a different question: which things are in the same group? Picture people at a party. At first everyone stands alone. Each time two people shake hands, their whole groups merge. Union-find can tell you at any time whether two people are now connected, almost instantly.
Both structures show up in interviews because they turn slow searches into fast ones. A trie makes prefix questions take time proportional to the word length. Union-find makes "are these connected?" nearly constant time, even as connections keep arriving.
Press Play on a diagram to walk through it one step at a time.
- c then a
- r (end of car)
- t (end of cat)
- d then o
- g (end of dog)
- Step 1Each node alone
parent[i] = i, every node its own root
- Step 2find(x)
Follow parents to the root, compressing the path
- Step 3union(a, b)
Attach the smaller root under the larger
- Step 4Same root?
Then a and b are connected
- 1Start
5 separate groups: 0, 1, 2, 3, 4
- 2union(0, 1)
Roots differ: merge, 4 groups
- 3union(1, 2)
Roots differ: merge, 3 groups
- 4union(3, 4)
Roots differ: merge, 2 groups
- 5Answer
5 nodes minus 3 merges = 2 components
In depth
Children: array or hash map?
Each trie node needs a way to find its child for the next letter. If the words use only lowercase English letters, a fixed array of 26 slots is fastest: the child for c is at index c - 'a'. The cost is memory: every node carries 26 pointers even if it uses one.
A hash map of children uses memory only for letters that exist and works for any characters, such as Unicode or mixed case, but each step is a little slower. Either way, insert and search cost O(L) for a word of length L, no matter how many words are stored. The total memory is at most the number of characters inserted, and less when words share prefixes.
- Array of 26: fast, more memory, lowercase only
- Hash map: flexible, less memory per node
- Insert and search: O(L)
- Memory: at most total characters stored
Prefix queries, autocomplete and deletion
startsWith(prefix) is a search that does not check the end flag at the last node. Autocomplete walks to the prefix node, then runs a DFS below it to collect words. Real autocomplete systems often store a small list of the top suggestions on each node, so they do not search the whole subtree on every keystroke.
To count how many words start with a prefix, keep a counter on each node and add 1 to every node you pass during insert. To delete a word, clear its end flag; then, walking back up, remove nodes that have no children and no end flag, so dead branches do not waste memory.
Word Search II: letting the trie drive the grid search
Word Search II asks which words from a list appear in a letter grid. Running the single-word search once per word repeats a lot of work. Instead, insert all words into a trie. Then start a DFS from every cell, and only step to a neighbour if its letter is a child of the current trie node. Words that share a prefix are explored together in one walk.
Store the whole word on its end node. When the DFS reaches a node with a word, add it to the results and remove it from the node so it is reported only once. A common speed-up is to delete trie branches that become empty, so later searches stop even sooner.
- 1Build the trie
Insert every word; store it on its end node
- 2Start at each cell
Only if its letter is a child of the root
- 3Step to neighbours
Only letters that are children of the current node
- 4Found a word node
Record the word, then clear it
- 5Restore and prune
Unmark the cell; drop empty branches
Union-find under the hood
Union-find (also called disjoint set union, or DSU) stores a parent array. Each group is a tree, and the root is the group's name. find(x) follows parents up to the root. union(a, b) finds both roots and, if they differ, points one root at the other.
Two tricks make it fast. Path compression makes every node you pass during find point closer to the root (path halving points each node to its grandparent), so later finds are short. Union by size (or by rank) always attaches the smaller tree under the larger one, so trees stay shallow. With both, each operation costs O(α(n)) amortised. α is the inverse Ackermann function, which is at most 4 for any input that fits in the universe, so treat it as constant.
- 4 points to 3
- 3 points to 2
- 2 points to 1, the root
- find(4) takes 3 steps
- 4 points to 1
- 3 points to 1
- 2 points to 1
- Next find(4) takes 1 step
When union-find beats BFS or DFS
For a fixed graph you can count components with BFS or DFS just as well. Union-find shines when edges arrive one at a time and you need answers in between, such as "how many islands after each new land cell?" (Number of Islands II). It also finds the edge that creates a cycle in an undirected graph (Redundant Connection): if union(a, b) finds that a and b already share a root, that edge closes a loop.
Other uses: grouping accounts that share an email (Accounts Merge), checking equations like a == b and b != c, and Kruskal's algorithm for minimum spanning trees. The one thing it cannot do is split a group again, so problems that delete edges need a different approach.
Learn it in 4 short steps
About 1h each. Track them with a timer in your plan.
- 1Implement a trie with insert and search~1h
- 2Implement union-find with path compression~1h
- 3Practice: Implement Trie, Word Search II~1h
- 4Practice: Number of Connected Components~1h
Key points
- Trie insert and search cost O(L), where L is the word length.
- Use a trie for prefix queries and Word Search II to prune the board search.
- Union-find with path compression and union by size is almost O(1) per operation.
- Count connected components as n minus the number of successful unions.
Key terms
Tap a card to flip it. 0/5 known
Examples
class Trie:
def __init__(self):
self.root = {}
def insert(self, word):
node = self.root
for ch in word:
node = node.setdefault(ch, {})
node['$'] = True # end-of-word marker
def search(self, word, prefix=False):
node = self.root
for ch in word:
if ch not in node:
return False
node = node[ch]
return prefix or '$' in nodesearch(w, prefix=True) answers startsWith.
Implement Trie with an array of 26 children
Insert "apple": create nodes a, p, p, l, e and set the end flag on e. search("app") walks a, p, p and finds the node, but its end flag is false, so it returns false. startsWith("app") only needs the node to exist, so it returns true. Insert "app" and the same node gets its end flag, so search("app") now returns true. Each call costs O(L) for a word of length L.
class Trie {
private final Trie[] next = new Trie[26]; private boolean isWord;
public void insert(String w) {
Trie node = this;
for (char ch : w.toCharArray()) {
int i = ch - 'a';
if (node.next[i] == null) node.next[i] = new Trie();
node = node.next[i];
}
node.isWord = true;
}
public boolean search(String w) { Trie n = walk(w); return n != null && n.isWord; }
public boolean startsWith(String p) { return walk(p) != null; }
private Trie walk(String s) { Trie n = this; for (char ch : s.toCharArray()) { n = n.next[ch - 'a']; if (n == null) return null; } return n; }
}Number of Connected Components: n = 5, edges [[0, 1], [1, 2], [3, 4]]
Start with 5 groups. Edge 0-1: roots 0 and 1 differ, merge, 4 groups. Edge 1-2: find(1) gives 0 (or 1, depending on which root won), find(2) gives 2, merge, 3 groups. Edge 3-4: merge, 2 groups. An edge whose ends already share a root would not reduce the count. The answer is 2. Union by size keeps the trees shallow, and path halving shortens them further on every find.
def count_components(n, edges):
parent, size = list(range(n)), [1] * n
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
groups = n
for a, b in edges:
ra, rb = find(a), find(b)
if ra == rb: continue # already connected
if size[ra] < size[rb]: ra, rb = rb, ra
parent[rb] = ra; size[ra] += size[rb] # smaller tree under larger
groups -= 1
return groupsQuick reference
- Trie node: 26 child slots (lowercase only) or a hash map (any characters), plus an end flag
- Trie insert, search and startsWith each cost O(L) for a word of length L
- Prefix counts: add 1 to a counter on every node passed during insert
- Word Search II: store the word on its end node and clear it once found
- Path compression plus union by size: amortised O(α(n)), effectively constant
- union finding both ends already share a root means that edge closes a cycle
- Components = n minus the number of successful unions
- Union-find cannot split groups; problems that delete edges need another method
Common mistakes
- Forgetting the end marker, so prefixes count as words.
- Union-find without path compression, degrading to O(n) finds.
- Unioning nodes instead of their roots.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Add a countPrefix(prefix) operation to a trie that returns how many inserted words start with the prefix.
- Exercise 2medium
Redundant Connection: a tree with nodes 1 to n had one extra edge added. Return the edge that, if removed, leaves a tree (the last such edge in the input).
- Exercise 3hard
Number of Islands II: an m x n grid starts as all water. positions lists cells that turn into land one by one. After each addition, return the number of islands.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use a trie or a hash set for a word list?
- A hash set is simpler and fast for exact lookups. Choose a trie when you need prefix queries, autocomplete, or to prune a search as soon as no word continues with the current letters.
- What is the difference between union by rank and union by size?
- Union by size attaches the tree with fewer nodes under the bigger one; union by rank uses an upper bound on tree height instead. Both keep trees shallow and give the same complexity, so use whichever you remember.
- Is union-find used outside interviews?
- Yes. It powers Kruskal's minimum spanning tree algorithm, grouping connected pixels in image processing, and finding which machines are linked in a network.