Two Specialized Structures That Finish the Interview Toolkit
After arrays, trees, graphs, and dynamic programming are steady, two compact structures close out the core interview pattern map: Union-Find (Disjoint Set Union) for dynamic connectivity and Tries for prefix-indexed string search. Both replace repeated full scans with small structural pointers.
Just as importantly, both reward sharp complexity analysis. Knowing Big-O notation is not a ritual for the final two minutes of an interview; reading constraints first tells you immediately whether a structure fits the time and memory budget.
Diagram: Original vector diagram by Ajay Kumar Chaturvedi (CC BY 4.0).
Intuition: DSU Compression, Prefix Branching, and Complexity Budgets
1. Union-Find: shrinking trees with every lookup
If a graph is fixed upfront, one DFS or BFS finds all connected components cleanly. Once edges arrive incrementally ("merge accounts," "redundant connection," "Kruskal minimum spanning tree"), running DFS after every edge costs .
As proven in the CP-Algorithms Disjoint Set Union chapter, combining two simple invariants drops each find and union to amortized time, where is the inverse Ackermann function (at most for every practical dataset up to ):
- Union by size: Always attach the smaller tree's root beneath the larger tree's root, bounding worst-case height to even alone.
- Path compression: During
find(x), point every visited node straight toward its root (iterative path halvingparent[x] = parent[parent[x]]runs in a tightwhileloop without recursion overhead).
When Union-Find appears on a 2D grid (for example, dynamic island queries as land cells appear one by one), flatten each (r, c) coordinate into a single integer ID r * cols + c rather than indexing (r, c) tuples inside nested dictionaries. Integer arrays keep memory tight and lookups cache-friendly.
2. Tries: indexing strings character by character
As summarized in the Wikipedia Trie reference, a trie stores keys along edge transitions rather than inside whole-key hash buckets. Looking up or inserting a word of length visits exactly child pointers (O(L)), independent of whether the dictionary holds ten words or ten million words.
While Python's dict and set answer exact membership (word in dict) in average hash time per Python built-in complexity notes, a hash set cannot answer starts_with("pre") or prune DFS branches on a 2D character grid when no dictionary word matches the current prefix.
3. Reading complexity budgets and separating auxiliary space
Before committing to any data structure, I glance at the input limits. An algorithm taking steps runs easily at , yet fails time limits once .
Equally important in interviews is separating auxiliary working space from output space: returning a list of all subsets ( output) still only uses auxiliary recursion depth, and stating both numbers explicitly prevents ambiguity when an interviewer probes memory limits. Keep track of hidden costs too, such as string slicing (s[i:j] copies characters in Python) and list front-pops (pop(0) takes shifts).
Diagram: Original vector diagram by Ajay Kumar Chaturvedi (CC BY 4.0).
Working Python Implementations
Here are clean, verified implementations of DisjointSet (with iterative path halving and component tracking) and Trie (using lightweight dict children and is_end markers).
class DisjointSet:
def __init__(self, n: int) -> None:
self.parent = list(range(n))
self.size = [1] * n
self.components = n
def find(self, x: int) -> int:
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]]
x = self.parent[x]
return x
def union(self, a: int, b: int) -> bool:
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
self.size[ra] += self.size[rb]
self.components -= 1
return True
class TrieNode:
def __init__(self) -> None:
self.children: dict[str, TrieNode] = {}
self.is_end = False
class Trie:
def __init__(self) -> None:
self.root = TrieNode()
def insert(self, word: str) -> None:
curr = self.root
for ch in word:
if ch not in curr.children:
curr.children[ch] = TrieNode()
curr = curr.children[ch]
curr.is_end = True
def search(self, word: str) -> bool:
node = self._walk(word)
return node is not None and node.is_end
def starts_with(self, prefix: str) -> bool:
return self._walk(prefix) is not None
def _walk(self, s: str) -> TrieNode | None:
curr = self.root
for ch in s:
if ch not in curr.children:
return None
curr = curr.children[ch]
return curr
if __name__ == "__main__":
dsu = DisjointSet(5)
assert dsu.union(0, 1)
assert dsu.union(1, 2)
assert not dsu.union(0, 2)
assert dsu.components == 3
trie = Trie()
for w in ("cat", "car", "card"):
trie.insert(w)
assert trie.search("car")
assert not trie.search("ca")
assert trie.starts_with("ca")
print("dsu components:", dsu.components)
print("trie search('car') / prefix('ca'):", trie.search("car"), trie.starts_with("ca"))Running this script produces:
dsu components: 3
trie search('car') / prefix('ca'): True TrueComplexity Analysis
| Structure / Operation | Time Complexity | Space Complexity | Nuance |
|---|---|---|---|
DSU find / union | amortized | Both path compression and union by size needed | |
Trie insert / search / starts_with | per string | worst | Shares common prefix nodes across words |
Hash set exact word in s | average | Hash step still reads characters of the string |
Notice an often-missed complexity detail: hash lookup on strings is not in string length , because computing the hash and verifying character equality costs . Where a Trie truly separates itself from a set is prefix queries (starts_with) and character-by-character backtracking pruning, without scanning every stored word.
Common Mistakes and When I Skip DSU or Tries
Watch out for these recurring pitfalls:
- Skipping union by size when implementing DSU: Path compression alone yields amortized, yet combining both adds three lines and secures worst-case protection.
- Returning `False` vs ignoring redundant unions: In cycle-detection problems (
Redundant Connection),union(u, v)returningFalsedirectly flags the edge that closes a cycle; skipping that boolean return forces redundantfindcalls outside the class. - Forgetting `is_end` on a Trie: Returning
Truewhenever_walk(word)succeeds causessearch("ca")to returnTruefalsely after inserting"cat". - Allocating fixed 26-element lists needlessly when alphabet varies: A
dictchild map handles lowercase ASCII, uppercase, digits, and Unicode uniformly without wasting 26 empty slots on sparse leaf nodes (though fixed[None] * 26arrays beatdictoverhead in pure lowercase memory benchmarks if tight).
I skip Union-Find when graph edges are directed (cycle detection or reachability in directed graphs needs topological sort or 3-color DFS, not undirected set merging) or when edges must be deleted dynamically (standard DSU cannot undo merges cleanly). Likewise, I skip Tries whenever queries only check exact whole-word membership and never inspect prefixes or wildcards, because a plain Python set uses far fewer object allocations per string.
Practice Problems
Test both structures on these two essential interview problems:
- Number of Connected Components in an Undirected Graph: Implement
DisjointSetcomponent counting and compare it with iterative DFS/BFS. - Implement Trie (Prefix Tree): Build
insert,search, andstarts_withwith a shared_walkhelper and verify prefix-only vs full-word matches.
