Advanced Graph Algorithms (Dijkstra, Topological Sort, Union-Find)
š Concept
Advanced graph algorithms solve complex real-world problems: navigation, task scheduling, network design, and more.
Dijkstra's Algorithm ā Shortest path (weighted, non-negative):
- Uses a priority queue (min-heap)
- Greedily explore the closest unvisited node
- Time: O((V + E) log V) with binary heap
Topological Sort ā Order tasks with dependencies:
- Only works on DAGs (Directed Acyclic Graphs)
- Two approaches: DFS-based (reverse postorder) or BFS-based (Kahn's algorithm with in-degrees)
- Used for: build systems, course scheduling, dependency resolution
Union-Find (Disjoint Set):
- Track connected components dynamically
- Operations: find(x) ā which component is x in?, union(x, y) ā merge components
- With path compression + union by rank: nearly O(1) per operation (amortized)
- Used for: Kruskal's MST, cycle detection, connected components
Minimum Spanning Tree (MST):
- Kruskal's: Sort edges, add cheapest that doesn't create cycle (uses Union-Find)
- Prim's: Grow tree from one vertex, always add cheapest edge (uses min-heap)
š Real-world analogy: Dijkstra = GPS finding shortest route considering road lengths. Topological sort = course prerequisites ā take CS101 before CS201. Union-Find = social network groups merging.
š» Code Example
1// DIJKSTRA ā Shortest path with weights2function dijkstra(graph, start) {3 const dist = new Map();4 const heap = new MinHeap(); // [distance, node]56 dist.set(start, 0);7 heap.push([0, start]);89 while (heap.size()) {10 const [d, u] = heap.pop();11 if (d > (dist.get(u) ?? Infinity)) continue; // Skip outdated1213 for (const [v, w] of graph.get(u) || []) {14 const newDist = d + w;15 if (newDist < (dist.get(v) ?? Infinity)) {16 dist.set(v, newDist);17 heap.push([newDist, v]);18 }19 }20 }21 return dist;22}2324// TOPOLOGICAL SORT ā Kahn's (BFS with in-degrees)25function topologicalSort(n, edges) {26 const graph = new Map();27 const inDegree = new Array(n).fill(0);28 for (let i = 0; i < n; i++) graph.set(i, []);29 for (const [u, v] of edges) {30 graph.get(u).push(v);31 inDegree[v]++;32 }3334 const queue = [];35 for (let i = 0; i < n; i++) {36 if (inDegree[i] === 0) queue.push(i);37 }3839 const order = [];40 while (queue.length) {41 const node = queue.shift();42 order.push(node);43 for (const neighbor of graph.get(node)) {44 inDegree[neighbor]--;45 if (inDegree[neighbor] === 0) queue.push(neighbor);46 }47 }4849 return order.length === n ? order : []; // Empty if cycle exists50}5152// UNION-FIND with path compression + union by rank53class UnionFind {54 constructor(n) {55 this.parent = Array.from({length: n}, (_, i) => i);56 this.rank = new Array(n).fill(0);57 this.components = n;58 }5960 find(x) {61 if (this.parent[x] !== x) {62 this.parent[x] = this.find(this.parent[x]); // Path compression63 }64 return this.parent[x];65 }6667 union(x, y) {68 const px = this.find(x), py = this.find(y);69 if (px === py) return false; // Already connected70 // Union by rank71 if (this.rank[px] < this.rank[py]) this.parent[px] = py;72 else if (this.rank[px] > this.rank[py]) this.parent[py] = px;73 else { this.parent[py] = px; this.rank[px]++; }74 this.components--;75 return true;76 }7778 connected(x, y) { return this.find(x) === this.find(y); }79}8081// COURSE SCHEDULE ā Can you finish all courses? (Cycle detection in DAG)82function canFinish(numCourses, prerequisites) {83 return topologicalSort(numCourses, prerequisites).length === numCourses;84}8586// NETWORK DELAY TIME ā Dijkstra on directed weighted graph87function networkDelayTime(times, n, k) {88 const graph = new Map();89 for (let i = 1; i <= n; i++) graph.set(i, []);90 for (const [u, v, w] of times) graph.get(u).push([v, w]);9192 const dist = dijkstra(graph, k);93 if (dist.size < n) return -1; // Not all reachable94 return Math.max(...dist.values());95}
šļø Practice Exercise
Practice Problems (Easy ā Hard):
- Implement Union-Find with path compression and union by rank
- Course schedule ā can you finish all courses? (cycle detection)
- Course schedule II ā find a valid order (topological sort)
- Network delay time ā Dijkstra's shortest path
- Number of provinces ā count connected components
- Redundant connection ā find the edge that creates a cycle
- Accounts merge ā union-find for grouping
- Cheapest flights within k stops ā modified Dijkstra/BFS
- Swim in rising water ā binary search + BFS/Union-Find
- Minimum spanning tree (Kruskal's algorithm)
ā ļø Common Mistakes
Using Dijkstra with negative weights ā it doesn't work! Use Bellman-Ford instead
Not using path compression in Union-Find ā without it, find is O(n) worst case
Topological sort on a cyclic graph ā result is incomplete; check if order.length === n
BFS for weighted shortest path ā BFS assumes all edges have weight 1; use Dijkstra for weights
Not using a priority queue for Dijkstra ā using simple array makes it O(V²) instead of O((V+E)logV)
š¼ Interview Questions
š¤ Mock Interview
Practice a live interview for Advanced Graph Algorithms (Dijkstra, Topological Sort, Union-Find)