11.3 Dijkstra's Shortest Path & Disjoint Set Union (Union-Find)
Master Dijkstra's Min-Heap Shortest Path for weighted graphs and Disjoint Set Union (Union-Find) for near-O(1) dynamic connectivity.
1. What Are Dijkstra's Algorithm & Union-Find?
- Dijkstra's Shortest Path Algorithm: Finds the minimum travel cost from a starting node
srcto every other node in a graph where edges have positive weights (distances/costs). - Disjoint Set Union (DSU / Union-Find): A data structure that tracks how
Nitems are grouped into separate islands (connected components) as edges are added one by one, answering "AreAandBin the same group?" and "MergeA's group withB's group" in nearO(1)time.
2. Why Do We Need Them & How Do They Work?
Why Plain BFS Fails on Weighted Graphs (And Why Dijkstra Works)
In an unweighted graph, every step costs 1, so a FIFO Queue (BFS) discovers nodes in order of distance.
When edges have weights, a direct edge A -> B might cost 100, while a 2-step detour A -> C -> B costs 2 + 3 = 5!
Dijkstra's Algorithm replaces the FIFO Queue with a Min-Heap of (distance_so_far, node):
- Always pop the node
uwith the smallest total distance fromsrc. - For each neighbor
vwith edge weightw, check if going throughuis a shortcut (dist[u] + w < dist[v]). If yes, updatedist[v]and push(dist[v], v)into the Min-Heap!
How Disjoint Set Union (Union-Find) Works
Imagine every node starts as its own boss (parent[i] = i):
find(x): Followsparentpointers up to the root boss ofx's group, and flattens the tree (parent[x] = find(parent[x])— Path Compression) so future lookups are instant (O(1)).union(a, b): Finds the boss ofa(pa) and the boss ofb(pb). Ifpa == pb, they were already connected (meaning edge(a, b)creates an undirected cycle!). Otherwise, linkparent[pa] = pb.
Quick Decision Table: Which Shortest-Path Algorithm Should You Pick?
| Graph Type | Edge Weights | Best Algorithm | Time Complexity |
|---|---|---|---|
| Unweighted Graph / 2D Grid | All edges cost 1 | Standard BFS (FIFO Queue) | O(V + E) |
| Weighted Graph (Positive / Zero) | w >= 0 (road distances, network latency) | Dijkstra's Algorithm (Min-Heap) | O(E log V) |
Weighted Graph with 0 or 1 Only | w in {0, 1} | 0-1 BFS (Deque: push 0 front, 1 back) | O(V + E) |
| Weighted Graph with Negative Edges | w < 0 allowed (or at most K stops) | Bellman-Ford (O(V * E)) | O(V * E) |
Interactive Step-by-Step Trace: Dijkstra Relaxation & Union-Find Compression
See how Dijkstra finds cheaper paths and DSU merges components in O(1):
Going through Node 1 reduces Node 2's distance from 10 down to 5!
3. Basic Operations & Walkthroughs (All 4 Languages)
import heapq
# 1. Dijkstra's Shortest Path from src -> O(E log V)
def dijkstra(n: int, adj: list[list[tuple[int, int]]], src: int) -> list[int]:
dist = [float("inf")] * n
dist[src] = 0
pq = [(0, src)] # (distance, node)
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]:
continue # Skip outdated heap entry
for v, w in adj[u]:
if d + w < dist[v]:
dist[v] = d + w
heapq.heappush(pq, (dist[v], v))
return dist
# 2. Disjoint Set Union (Union-Find with Path Compression) -> O(alpha(N)) ≈ O(1)
class DSU:
def __init__(self, n: int):
self.parent = list(range(n))
def find(self, x: int) -> int:
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, a: int, b: int) -> bool:
pa, pb = self.find(a), self.find(b)
if pa == pb:
return False # Already in same component (cycle!)
self.parent[pa] = pb
return True4. Core Interview Patterns & Common Traps
Use Dijkstra for weighted shortest paths with non-negative weights; use Union-Find to count connected components or detect the exact edge that creates an undirected cycle.
# Union-Find Cycle & Component Counter:
components = n
for u, v in edges:
if dsu.union(u, v):
components -= 1 # Merged two separate islands!
else:
return [u, v] # u and v were ALREADY connected -> redundant cycle edge!| Operation / Pattern | Time | Space | Notes |
|---|---|---|---|
| Dijkstra's Shortest Path | O(E log V) | O(V + E) | Requires non-negative edge weights |
| Union-Find (find & union) | O(alpha(N)) ≈ O(1) | O(N) | Path compression flattens tree height |