Data Structures and Algorithms5 min read

Union-Find, Tries, and Complexity Analysis for Dynamic Graph and String Queries

How Disjoint Set Union tracks dynamic connectivity in near-constant amortized time, when a Trie outperforms hash sets on string prefix queries, and how to read input bounds for complexity targets.

Disjoint Set Union tracks dynamic connected components across edge additions in O(alpha(n)) amortized time per operation by pairing path compression with union by size or rank. A Trie stores strings along shared character edges to answer word and prefix lookups in O(L) time independent of dictionary count, while input constraints immediately indicate which asymptotic complexity class is viable.

Key takeaways

  • Choose Union-Find over repeated BFS/DFS whenever edges arrive dynamically or Kruskal MST requires cycle checks.
  • Reach for a Trie only when prefix matching, autocomplete, or word-board pruning justifies per-node dictionary memory.
  • State both time and auxiliary space complexity clearly, including input string lengths L and alphabet size.

Quick facts

  • Combining path compression and union by size keeps DSU amortized cost below 5 pointer hops for practical n.
  • Iterative path halving inside find avoids recursion depth errors on huge forests.
  • A Trie supports startsWith and wildcard DFS queries in O(L) where hash sets cannot index prefixes directly.
  • Checking constraints like n <= 10^5 reveals before coding that O(n log n) or O(n) is required.

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.

Disjoint set union path compression and Trie prefix tree architecture
Disjoint set union path compression and Trie prefix tree architecture

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 O(E⋅(V+E))O(E \cdot (V + E)).

As proven in the CP-Algorithms Disjoint Set Union chapter, combining two simple invariants drops each find and union to O(α(n))O(\alpha(n)) amortized time, where α(n)\alpha(n) is the inverse Ackermann function (at most 44 for every practical dataset up to 1060010^{600}):

  1. Union by size: Always attach the smaller tree's root beneath the larger tree's root, bounding worst-case height to O(log⁡n)O(\log n) even alone.
  2. Path compression: During find(x), point every visited node straight toward its root (iterative path halving parent[x] = parent[parent[x]] runs in a tight while loop 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 LL visits exactly LL 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 O(L)O(L) 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 O(n2)O(n^2) steps runs easily at n=500n = 500, yet fails time limits once n=105n = 10^5.

Equally important in interviews is separating auxiliary working space from output space: returning a list of all subsets (O(n⋅2n)O(n \cdot 2^n) output) still only uses O(n)O(n) 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 O(j−i)O(j - i) characters in Python) and list front-pops (pop(0) takes O(n)O(n) shifts).

Interview input constraint sizes mapped to target Big-O complexity budgets
Interview input constraint sizes mapped to target Big-O complexity budgets

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).

PYTHON
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:

TEXT
dsu components: 3
trie search('car') / prefix('ca'): True True

Complexity Analysis

Structure / OperationTime ComplexitySpace ComplexityNuance
DSU find / unionO(α(V))O(\alpha(V)) amortizedO(V)O(V)Both path compression and union by size needed
Trie insert / search / starts_withO(L)O(L) per stringO(N⋅L)O(N \cdot L) worstShares common prefix nodes across words
Hash set exact word in sO(L)O(L) averageO(N⋅L)O(N \cdot L)Hash step still reads LL characters of the string

Notice an often-missed complexity detail: hash lookup on strings is not O(1)O(1) in string length LL, because computing the hash and verifying character equality costs O(L)O(L). 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 O(log⁡n)O(\log n) amortized, yet combining both adds three lines and secures O(α(n))O(\alpha(n)) worst-case protection.
  • Returning `False` vs ignoring redundant unions: In cycle-detection problems (Redundant Connection), union(u, v) returning False directly flags the edge that closes a cycle; skipping that boolean return forces redundant find calls outside the class.
  • Forgetting `is_end` on a Trie: Returning True whenever _walk(word) succeeds causes search("ca") to return True falsely after inserting "cat".
  • Allocating fixed 26-element lists needlessly when alphabet varies: A dict child map handles lowercase ASCII, uppercase, digits, and Unicode uniformly without wasting 26 empty slots on sparse leaf nodes (though fixed [None] * 26 arrays beat dict overhead 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:

  1. Number of Connected Components in an Undirected Graph: Implement DisjointSet component counting and compare it with iterative DFS/BFS.
  2. Implement Trie (Prefix Tree): Build insert, search, and starts_with with a shared _walk helper and verify prefix-only vs full-word matches.

Sources