Sub topic 3
Union-find with union by rank and path compression
This chapter assumes you know Big-O notation, recursion, basic graph terms (vertices, weighted edges, connectivity), and binary heaps.
Union-find
Union-find, also called disjoint-set union, tracks which vertices belong to the same group. find(x) returns the representative of x's group, and union(a, b) merges two groups. Union by rank attaches the shorter tree under the taller one. Path compression points each visited node directly at its root. Together they give almost constant amortized time per operation, O(α(n)), where α is the inverse Ackermann function.
parent = list(range(5))
rank = [0] * 5
def find(x):
if parent[x] != x:
parent[x] = find(parent[x]) # path compression
return parent[x]
def union(a, b):
ra, rb = find(a), find(b)
if ra == rb:
return False
if rank[ra] < rank[rb]:
ra, rb = rb, ra
parent[rb] = ra
if rank[ra] == rank[rb]:
rank[ra] += 1
return True
print(union(0, 1), union(1, 0), union(2, 3)) # True False TrueSpanning trees and the cut property
A spanning tree connects all V vertices with V - 1 edges and no cycles. A minimum spanning tree (MST) has the smallest total weight. The cut property says that for any cut (a split of vertices into two sides), the lightest edge crossing the cut belongs to some MST. Greedy MST algorithms rely on this property.
Kruskal's and Prim's algorithms
Kruskal sorts edges by weight and keeps each edge that joins two different components, checked with union-find. It runs in O(E log E). Prim grows one tree from a start vertex and always adds the lightest edge leaving the tree. With a binary heap it runs in O(E log V).
Single-source shortest paths and relaxation
For each vertex v, dist[v] stores the best known distance from the source. Relaxing edge (u, v, w) sets dist[v] to dist[u] + w when that value is smaller. Shortest-path algorithms differ in the order they relax edges.
Dijkstra's algorithm and negative edges
Dijkstra always finalizes the closest unfinalized vertex. Its greedy choice is safe only when no edge weight is negative.
Consider edges S to A (2), S to B (3), and B to A (-2). Dijkstra finalizes A at distance 2, but the path S, B, A costs 1.
Bellman-Ford and negative cycles
Bellman-Ford relaxes every edge V - 1 times, so it handles negative edges. If an edge can still be relaxed after V - 1 rounds, a negative cycle is reachable from the source. Its time is O(VE).
Floyd-Warshall all-pairs shortest paths
Floyd-Warshall computes shortest paths between all pairs using three nested loops over an adjacency matrix. It runs in O(V^3). It handles negative edges but not negative cycles.
Choosing greedy or dynamic programming
Use a greedy method when a locally best choice is provably safe, usually by an exchange argument or the cut property. Use dynamic programming (DP) when choices interact and an optimal answer combines optimal answers to subproblems. Fractional knapsack is solved greedily by value-to-weight ratio. 0/1 knapsack needs DP, because a greedy ratio choice can miss the optimum.
Exercise
Why does Dijkstra's algorithm fail on the graph S to A (2), S to B (3), B to A (-2)?
Show answer
Dijkstra finalizes A at distance 2 before it considers the edge from B. The path S, B, A has cost 3 + (-2) = 1, which is smaller. Once a vertex is finalized, Dijkstra never revises it, so the answer is wrong. Bellman-Ford handles this graph correctly.