Trees, Tries, Graph Traversal (BFS/DFS/Dijkstra/Topological Sort) & Union-Find

Intermediate-to-advanced Tree and Graph algorithm patterns covering iterative and Morris O(1)-space tree traversals, BST validation, LCA, Tree Serialization, Prefix & Bitwise Tries, 0-1 and Multi-Source BFS, 3-color DFS cycle detection, Kahn's & DFS Topological Sort, Dijkstra, Bellman-Ford, Floyd-Warshall, Union-Find (DSU), MST (Kruskal/Prim), and Tarjan's Bridges.

Category
Coding Interviews (Blind 75 / NeetCode DSA), Distributed System Design & Advanced SQL
Level
intermediate
Languages
en → en
Cards
32
Markdown
Trees, Tries, Graph Traversal (BFS/DFS/Dijkstra/Topological Sort) & Union-Find (.md)

Flashcards (32)

#Front (Term / Question)Back (Definition / Answer)ExampleMultiple-Choice Options
1How do you implement a Prefix `Trie` (`LeetCode 208`) and how does it accelerate backtracking in `Word Search II` (`LeetCode 212`)?Each `TrieNode` holds a dictionary/26-array `children` and an `is_word` flag (or stores the completed `word` string). Inserting and searching a word of length $L$ takes $O(L)$ time. In `Word Search II` (finding 30,000 dictionary words on an $M \times N$ board), running separate DFS for each word is way too slow; instead, insert all words into one Prefix Trie and traverse the board and the Trie simultaneously—pruning any board path immediately when `board[r][c]` is not in `trie_node.children` (and deleting leaf Trie nodes once a word is found)!
2Why does cycle detection in a Directed Graph (`Course Schedule`, `LeetCode 207`) require 3 states (`0=Unvisited`, `1=Visiting`, `2=Visited`) in DFS, whereas an Undirected Graph only needs `visited` + `parent`?In an Undirected Graph, any edge to an already-visited node `v != parent` immediately forms a cycle. In a Directed Graph, reaching an already-finished node (`state == 2`) from another branch is a benign **cross edge or forward edge** (like a diamond DAG `A -> B -> D` and `A -> C -> D`), NOT a cycle! A directed cycle exists if and only if DFS encounters a **back edge** to a node currently on the active recursion stack (`state == 1 = Visiting`).
3Why does simply checking `node.left.val < node.val < node.right.val` fail to validate a Binary Search Tree (`LeetCode 98 Validate BST`), and what is the correct $O(n)$ approach?Checking only immediate children fails when a deeper descendant violates an ancestor's bound (e.g., root `5`, right child `7`, and `7`'s left child is `3`—`3 < 7` locally, but `3 < 5` violates the root's right subtree invariant!). Correct approaches: 1. Pass `(low, high)` bounds top-down: `validate(node, low, high)` checks `low < node.val < high` and recurses `validate(node.left, low, node.val)` and `validate(node.right, node.val, high)`; OR 2. Verify that an Inorder Traversal produces strictly increasing values (`prev < curr.val`).
4How do you solve `Alien Dictionary` (`LeetCode 269`) using Topological Sort, and what is the critical prefix edge case?Compare each adjacent pair of words `(w1, w2)` in the sorted dictionary and find the FIRST index $i$ where `w1[i] != w2[i]`: add directed edge `w1[i] -> w2[i]` and `break` (subsequent characters in `w1` and `w2` give no ordering info!). CRITICAL EDGE CASE: If `w1` is longer than `w2` and `w2` is a prefix of `w1` (e.g., `["abc", "ab"]`), that violates lexicographical rules—immediately return `""`! Finally run Kahn's BFS over all unique characters.
5How do you compute the `Diameter of a Binary Tree` (`LeetCode 543`) and `Binary Tree Maximum Path Sum` (`LeetCode 124`) in a single $O(n)$ Post-Order DFS pass?In both problems, carefully distinguish between: (a) what a node **updates in the global answer** (a path that bends/peaks at `node` using BOTH `left_gain + right_gain`), versus (b) what `dfs(node)` **returns to its parent** (a straight path that can only pick ONE branch: `max(left_gain, right_gain)`!). In `Max Path Sum` (`LC 124`), clamp negative child contributions to zero (`left_gain = max(0, dfs(node.left))`), update `best = max(best, node.val + left_gain + right_gain)`, and return `node.val + max(left_gain, right_gain)`.
6Explain Dijkstra's Shortest Path Algorithm, its time complexity with a Binary Heap, and why it fails on negative edge weights.Initialize `dist = [inf] * V`, `dist[src] = 0`, and `pq = [(0, src)]`. While `pq`: pop `(d, u) = heappop(pq)`. **Lazy deletion skip**: `if d > dist[u]: continue`! For each `(v, w)` in `adj[u]`: `if d + w < dist[v]: dist[v] = d + w; heappush(pq, (dist[v], v))`. Time complexity: $O((V + E) \log V)$ because at most $E$ entries are pushed into the heap. Dijkstra fails with negative edge weights because it greedily assumes that once the minimum-distance node `u` is popped from `pq`, no future longer path can ever later traverse a negative edge to beat `dist[u]`.
7How do you find an Eulerian Path (`Reconstruct Itinerary`, `LeetCode 332`) in $O(E \log E)$ time using Hierholzer's Algorithm?An Eulerian Path visits every directed **edge** (flight ticket) exactly once. Sort each airport's adjacency list in reverse lexicographical order so popping from the end (`adj[u].pop()`) yields the smallest lexical neighbor in $O(1)$ time. Run post-order DFS (`def dfs(u): while adj[u]: dfs(adj[u].pop()); route.append(u)`): whenever a node gets stuck with no remaining outgoing edges, it must be the end of the remaining tour (or a side loop), so append `u` to `route` in post-order and return `route[::-1]`!
8How do you perform Iterative Preorder, Inorder, and Postorder Binary Tree traversals using an explicit Stack?Preorder (`Root, L, R`): Push `root`; while stack: pop `node`, visit it, then push `node.right` followed by `node.left` (so `left` is popped first). Inorder (`L, Root, R`): Initialize `curr = root`; while `curr or stack`: drill left (`while curr: stack.append(curr); curr = curr.left`), pop `curr = stack.pop()`, visit `curr`, then step right `curr = curr.right`. Postorder (`L, R, Root`): Either reverse a Modified Preorder (`Root, R, L`), or track `last_visited` when peeking at the stack top before popping.
9What is the Tree Rerooting DP technique (`Sum of Distances in Tree`, `LeetCode 834`) that computes an all-roots metric in $O(n)$ instead of $O(n^2)$?Use Two DFS Passes: Pass 1 (Post-Order Bottom-Up from root `0`): Compute subtree sizes `count[u]` (number of nodes in `u`'s subtree) and `ans[0]` (sum of distances from root `0` to all nodes). Pass 2 (Pre-Order Top-Down rerooting from parent `u` to child `v`): When moving the root across edge `u -> v`, all `count[v]` nodes in `v`'s subtree get 1 step CLOSER, while all remaining `n - count[v]` nodes outside `v`'s subtree get 1 step FURTHER away! So `ans[v] = ans[u] - count[v] + (n - count[v])` in $O(1)$ per edge!
10How does the $A^*$ (A-Star) Search algorithm improve upon Dijkstra's algorithm, and what makes a heuristic $h(n)$ 'Admissible' and 'Consistent'?$A^*$ orders the priority queue by $f(n) = g(n) + h(n)$, where $g(n)$ is the exact cost from start to $n$, and $h(n)$ is a heuristic estimate of remaining cost from $n$ to the goal. $h(n)$ is **Admissible** if it NEVER overestimates the true remaining distance ($0 \le h(n) \le h^*(n)$, e.g., Manhattan distance on a 4-dir grid or Euclidean distance), guaranteeing $A^*$ finds the optimal shortest path. $h(n)$ is **Consistent** (Monotone) if $h(u) \le w(u, v) + h(v)$ (triangle inequality), guaranteeing nodes never need to be re-expanded after being popped.
11How do you uniquely reconstruct a Binary Tree from `Preorder + Inorder` (`LeetCode 105`) in $O(n)$ time instead of $O(n^2)$?`Preorder`'s first element is always the subtree root; locating that value inside `Inorder` splits `Inorder` into the left subtree (`[in_left .. idx - 1]`) and right subtree (`[idx + 1 .. in_right]`). Prebuild a Hash Map `in_map = {val: i for i, val in enumerate(inorder)}` so looking up `idx` takes $O(1)$ instead of $O(n)$, and pass index bounds `(in_left, in_right)` rather than slicing arrays—achieving strict $O(n)$ time and $O(n)$ space. Note: `Preorder + Postorder` CANNOT uniquely reconstruct a general binary tree (unless every internal node has 2 children)!
12How do you find the Kth Ancestor of a Tree Node (`LeetCode 1483`) or LCA in $O(\log V)$ per query using Binary Lifting?Precompute a table `up[u][j]` of size $V \times \lceil \log_2 V \rceil$ in $O(V \log V)$ time, where `up[u][0] = parent[u]` and `up[u][j] = up[ up[u][j - 1] ][j - 1]` (the $2^j$-th ancestor of node $u$). Then to jump $k$ levels up from node $u$, iterate over the set bits $j$ of the binary representation of $k$ (`if (k >> j) & 1: u = up[u][j]`), reaching the $k$-th ancestor in at most $\log_2 V$ hops!
13Compare Adjacency List and Adjacency Matrix graph representations in terms of space, edge lookup, and neighbor iteration complexity.Adjacency List (`dict`/`vector` of neighbor lists): $O(V + E)$ space; $O(\text{deg}(u))$ to iterate over neighbors of $u$; $O(\text{deg}(u))$ (or $O(1)$ with hash sets) to check if edge $(u, v)$ exists; optimal for **sparse graphs** ($E \ll V^2$), which includes almost all interview graphs. Adjacency Matrix ($V \times V$ grid): $O(V^2)$ space; $O(1)$ to check if edge $(u, v)$ exists; $O(V)$ to iterate over neighbors of $u$; used only for **dense graphs** ($E \approx V^2$) or Floyd-Warshall.
14How do a Fenwick Tree (Binary Indexed Tree) and a Segment Tree solve dynamic Range Sum / Range Minimum Queries with Point Updates (`LeetCode 307`)?Prefix Sums do $O(1)$ range query but $O(n)$ point update. A **Fenwick Tree (BIT)** uses a 1-indexed array `bit` of size $n + 1$ where `add(i, delta)` loops `while i <= n: bit[i] += delta; i += i & -i` and `query(i)` loops `while i > 0: s += bit[i]; i -= i & -i`—performing BOTH point updates and prefix queries in $O(\log n)$ time with ~10 lines of code! A **Segment Tree** builds a binary tree over array intervals (`4n` array size) supporting any associative operation (min, max, GCD, sum) plus Lazy Propagation for $O(\log n)$ range updates.
15Explain the Bellman-Ford Algorithm, how it detects Negative Weight Cycles, and its time complexity.Since any shortest simple path in a graph with $V$ vertices contains at most $V - 1$ edges, Bellman-Ford relaxes ALL $E$ edges (`if dist[u] + w < dist[v]: dist[v] = dist[u] + w`) for $V - 1$ iterations, taking $O(V \cdot E)$ time and $O(V)$ space. To detect a Negative Weight Cycle reachable from the source, run a $V$-th relaxation pass over all $E$ edges: if any `dist[v]` still decreases on the $V$-th pass, a negative cycle exists!
16Compare finding the Lowest Common Ancestor (LCA) in a general Binary Tree (`LeetCode 236`) vs. a Binary Search Tree (`LeetCode 235`).In a BST (`LC 235`, $O(H)$ time, $O(1)$ space): Use value ordering! While `curr`: if both `p.val < curr.val` and `q.val < curr.val`, go left (`curr = curr.left`); if both `> curr.val`, go right; otherwise `curr` is the split point (the LCA!). In a general Binary Tree (`LC 236`, $O(n)$ time): If `not root or root == p or root == q: return root`. Recurse `L = lca(root.left, p, q)` and `R = lca(root.right, p, q)`. If both `L and R` are non-null, `root` is the LCA; otherwise return `L or R`.
17How does a Bitwise Trie (0/1 Binary Trie) solve 'Maximum XOR of Two Numbers in an Array' (`LeetCode 421`) in $O(32n)$ time?Insert the 32-bit binary representation of every number into a binary Trie from Most Significant Bit (bit 31) down to Least Significant Bit (bit 0). To maximize $x \oplus y$ for a given $x$, walk down the Trie from bit 31 to 0, greedily choosing the **opposite bit** `1 - bit` at each level whenever that child branch exists (since $2^{31} > \sum_{k=0}^{30} 2^k$, setting a single higher bit beats all lower bits combined!).
18Explain Tarjan's Algorithm for finding Bridges (`Critical Connections in a Network`, `LeetCode 1192`) and Articulation Points in a single $O(V + E)$ DFS pass.Maintain two arrays during DFS: `disc[u]` (discovery timestamp when `u` is first visited) and `low[u]` (the lowest discovery timestamp reachable from `u`'s DFS subtree using at most one back-edge). For each neighbor `v` of `u` (where `v != parent`): if `v` is already visited, update `low[u] = min(low[u], disc[v])`; if `v` is unvisited, recurse on `v`, update `low[u] = min(low[u], low[v])`, and check: **Edge `(u, v)` is a Bridge if and only if `low[v] > disc[u]`** (meaning `v`'s subtree has NO back-edge reaching `u` or an ancestor of `u`!).
19How do you check if a graph is Bipartite (`Is Graph Bipartite?` `LeetCode 785`, `Possible Bipartition` `LC 886`)?A graph is bipartite (its vertices can be partitioned into two independent sets such that every edge connects nodes of different sets) if and only if it is **2-colorable** (equivalently, contains **no odd-length cycles**). Iterate over all components and run BFS/DFS with a `color` array initialized to `0` (`uncolored`): color the start node `1`, and for every neighbor `nei` of `u`, if `color[nei] == 0`, assign `color[nei] = -color[u]`; if `color[nei] == color[u]`, return `False`.
20How does Bidirectional BFS improve the time complexity of `Word Ladder` (`LeetCode 127`)?Standard BFS with branching factor $b$ and shortest path depth $d$ explores $O(b^d)$ states. Bidirectional BFS maintains two frontier sets (`begin_set = {beginWord}` and `end_set = {endWord}`) and at each step always expands the **smaller** of the two frontier sets by one level until the two frontiers intersect—reducing explored states from $O(b^d)$ to $O(2 \cdot b^{d/2})$!
21How do you `Serialize and Deserialize a Binary Tree` (`LeetCode 297`) in $O(n)$ time?Use Preorder DFS with explicit null markers (`"#"`) and comma delimiters: `serialize(node)` outputs `"#"` if `node is None`, else `f"{node.val},{serialize(node.left)},{serialize(node.right)}"`. To `deserialize(data)`: create an iterator `vals = iter(data.split(","))`; define `build()`: take `v = next(vals)`; if `v == "#"`, return `None`; else create `node = TreeNode(int(v))`, set `node.left = build()`, `node.right = build()`, and return `node`!
22How does Multi-Source BFS work (`Rotting Oranges` `LC 994`, `01 Matrix` `LC 542`, `Walls and Gates` `LC 286`), and why must you mark nodes `visited` at ENQUEUE time rather than DEQUEUE time?Instead of running a separate BFS from every source (which would take $O(V \cdot (V+E))$), push **all starting source nodes simultaneously into the queue at distance `0`** before starting the BFS loop—computing shortest distance from every cell to its nearest source in a single $O(V + E)$ pass! CRITICAL: Always mark a neighbor as `visited` the moment you push it onto `deque` (enqueue time), NOT when you pop it! Marking on pop allows the same unpopped node to be pushed into the queue multiple times by different neighbors, causing Memory/Time Limit Exceeded.
23Explain 0-1 BFS (`Minimum Obstacle Removal to Reach Corner`, `LeetCode 2290`) and why it runs in $O(V + E)$ instead of $O((V + E) \log V)$ Dijkstra.When all edge weights in a graph are strictly `0` or `1`, we don't need a priority queue! Use a `collections.deque`: when relaxing an edge $(u, v)$ with weight `w` that improves `dist[v] = dist[u] + w`: if `w == 0`, push `v` to the **FRONT** of the deque (`dq.appendleft(v)`); if `w == 1`, push `v` to the **BACK** of the deque (`dq.append(v)`). This preserves the monotonic distance invariant in the deque in $O(1)$ per edge ($O(V + E)$ total time)!
24How does BFS vs. DFS compare for finding the shortest path in an unweighted grid (`Shortest Path in Binary Matrix` `LC 1091`) vs. exhausting all paths (`Word Search` `LC 79`)?For **Shortest Path in an unweighted graph/grid**, ALWAYS use **BFS**! Because BFS explores level-by-level by distance $d = 0, 1, 2, \dots$, the very first time BFS reaches the target cell, it is mathematically guaranteed to be the shortest path in $O(V + E)$ time (whereas DFS would have to explore all exponential paths or relax distances repeatedly). For **Path Existence with backtracking state** (where visited cells must be unmarked upon returning, like `Word Search` `LC 79`), use **DFS with Backtracking** (`O(H)` call-stack space vs $O(W)$ BFS frontier).
25Write the complete Disjoint Set Union (Union-Find / DSU) implementation with Path Compression and Union by Rank/Size, and state its complexity.Initialize `parent = list(range(n))` and `size = [1] * n`. `def find(x): if parent[x] != x: parent[x] = find(parent[x]); return parent[x]` (Path Compression flattens trees directly to the root). `def union(a, b): ra, rb = find(a), find(b); if ra == rb: return False; if size[ra] < size[rb]: ra, rb = rb, ra; parent[rb] = ra; size[ra] += size[rb]; return True` (Union by Size attaches the smaller tree under the larger root). Combining both optimizations achieves $O(\alpha(V))$ amortized time per operation, where $\alpha(V) \le 4$ is the Inverse Ackermann function (effectively $O(1)$!).
26How does Morris Traversal achieve $O(n)$ time and $O(1)$ auxiliary space (no recursion or stack!) for Inorder Binary Tree traversal?Morris Traversal temporarily threads the right pointer of each node's **inorder predecessor** (the rightmost node in `curr.left`'s subtree) back to `curr`: 1. If `curr.left is None`, visit `curr` and advance `curr = curr.right`. 2. Otherwise, find `pred = curr.left` (`while pred.right and pred.right is not curr: pred = pred.right`): (a) If `pred.right is None`, create thread `pred.right = curr` and move `curr = curr.left`; (b) If `pred.right is curr` (left subtree finished!), remove thread `pred.right = None`, visit `curr`, and move `curr = curr.right`. Each edge is traversed at most 3 times ($O(n)$ time, $O(1)$ space).
27Compare Kahn's Algorithm (BFS with In-Degrees) and Post-Order DFS for Topological Sorting of a Directed Acyclic Graph (DAG).Kahn's Algorithm (BFS): 1. Compute `in_degree[v]` for all nodes in $O(V + E)$; 2. Push all nodes with `in_degree[v] == 0` into a queue; 3. While queue: pop `u`, append `u` to `topo_order`, and for each `v` in `adj[u]`, decrement `in_degree[v] -= 1`—if `in_degree[v] == 0`, push `v`. If `len(topo_order) < V`, the graph contains a cycle! Post-Order DFS: Run 3-state cycle-detecting DFS; append each node to `order` only AFTER all its outgoing neighbors finish (`state = 2`), then reverse `order`.
28How do you solve Longest Path or Dynamic Programming on a DAG (e.g., `Parallel Courses III` `LC 2050`, `Largest Color Value in a Directed Graph` `LC 1857`)?Any DAG has a Topological Ordering where every edge $(u, v)$ points strictly forward. Process nodes in Kahn's BFS topological order while relaxing a DP table along outgoing edges: when visiting `u`, for each neighbor `v` in `adj[u]`, update `dp[v] = max(dp[v], dp[u] + cost(v))` before decrementing `in_degree[v]`. This solves longest/optimal path in a DAG in $O(V + E)$ linear time (whereas longest simple path in a general cyclic graph is NP-Hard!).
29Explain the Floyd-Warshall All-Pairs Shortest Path algorithm and why the intermediate vertex loop `k` MUST be the outermost loop.Floyd-Warshall is a space-optimized Dynamic Programming algorithm where `dp[k][i][j]` is the shortest path from $i$ to $j$ using only intermediate vertices from $\{0, 1, \dots, k\}$. Three nested loops in $O(V^3)$ time and $O(V^2)$ space: `for k in range(V): for i in range(V): for j in range(V): dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])`. `k` MUST be the outer loop because phase `k` relies on all pairs `dist[i][k]` and `dist[k][j]` already having been optimal across intermediate vertices $0 \dots k-1$! (If `dist[i][i] < 0` after completion, node $i$ is on a negative cycle).
30What problem patterns are immediately solved by Disjoint Set Union (Union-Find)?1. Counting Connected Components dynamically (`Number of Provinces` `LC 547`, `Number of Islands II` `LC 305` where land cells are added online); 2. Detecting the first edge that creates a cycle in an undirected graph (`Redundant Connection` `LC 684`—if `union(u, v)` returns `False`, edge `(u, v)` closes a cycle); 3. Equivalence partitioning / transitive grouping (`Accounts Merge` `LC 721`, `Smallest String With Swaps` `LC 1202`, `Evaluate Division` `LC 399` using weighted DSU).
31How do you modify Dijkstra's Algorithm when paths have a secondary constraint (e.g., `Cheapest Flights Within K Stops` `LC 787`, `Swim in Rising Water` `LC 778`, `Path With Minimum Effort` `LC 1631`)?1. Bottleneck Minimax Path (`LC 778` / `LC 1631`): Replace path sum `d + w` with path bottleneck `max(d, edge_effort)`—since `max` is monotonically non-decreasing, Dijkstra's greedy invariant holds in $O(E \log V)$! 2. State-Space Dijkstra (`LC 787` Cheapest Flights Within K Stops): If you prune solely by `dist[u]`, you might discard a slightly more expensive path that used FEWER stops and could still reach destination within $K$ stops! Track `min_stops[u]`—still explore `(cost, u, stops)` if `stops < min_stops[u]` (or use $K + 1$ rounds of Bellman-Ford).
32Compare Kruskal's Algorithm and Prim's Algorithm for finding a Minimum Spanning Tree (MST, e.g., `Min Cost to Connect All Points` `LeetCode 1584`).An MST connects all $V$ vertices of a connected undirected graph using $V - 1$ edges with minimum total weight. 1. Kruskal's Algorithm (edge-centric): Sort all $E$ edges by weight in $O(E \log E)$ time; iterate through sorted edges and add edge $(u, v)$ if `dsu.union(u, v)` returns `True` (no cycle) until $V - 1$ edges are chosen—best for sparse graphs. 2. Prim's Algorithm (vertex-centric): Grow a single tree from node `0` using a Min-Heap (or array of min distances in $O(V^2)$ for dense complete graphs like `LC 1584`) to repeatedly add the cheapest edge crossing from visited to unvisited vertices.