Advanced Graphs
Ripples on a pond reach the closest shore first. Dijkstra works the same way: always finish the nearest place you know about, because nothing later can get there sooner. Union-Find is the other tool here: give every group one leader, and two people are in the same group when they name the same leader.
2 · Watch
Advanced Graphs in 60 seconds
3 · Now you drive
Network Delay Time
4 · Your turn
Start from this
// Dijkstra: the heap hands back the closest node first.
const best = new Array(n).fill(Infinity);
best[start] = 0;
const heap = new MinHeap([[0, start]]);
while (heap.size() > 0) {
const [time, node] = heap.pop();
// Old entry: a faster way here was already found.
if (time > best[node]) continue;
for (const [next, cost] of roads[node]) {
// A cheaper way to next? Save it and queue it.
if (time + cost < best[next]) {
best[next] = time + cost;
heap.push([best[next], next]);
}
}
}
// Union-Find: each node points toward its group's leader.
const parent = Array.from({ length: n }, (_, i) => i);
const find = (x: number): number => {
// Point straight at the leader, so the next find is quick.
if (parent[x] !== x) parent[x] = find(parent[x]);
return parent[x];
};
// Join two groups. False means they were already one group,
// so this link closes a loop.
const union = (a: number, b: number): boolean => {
const leaderA = find(a), leaderB = find(b);
if (leaderA === leaderB) return false;
parent[leaderB] = leaderA;
return true;
};Easy ways to go wrong
- Using Dijkstra with negative costs. It assumes a finished node can't get cheaper.
- Skipping the old-entry check, which redoes work on finished nodes.
- Reading parent[x] directly. That may not be the leader, so call find(x).
- Dropping the shortcut in find, which lets long chains slow every lookup.
- Medium01
Number of Connected Components in an Undirected Graph
LeetCode PremiumStart with n groups. Each useful link removes one.
Flood from each unvisited node, or join groups as you read the links.
- Time
- O(V + E)
- Space
- O(V + E)
Also works with Graphs.
- Medium02
Graph Valid Tree
LeetCode PremiumA link inside one group means a loop.
Exactly n − 1 links, and one flood reaches everyone.
- Time
- O(V + E)
- Space
- O(V + E)
Also works with Graphs or Trees.
- Hard03
Alien Dictionary
LeetCode PremiumTurn word pairs into arrows, then sort them.
Each neighbouring word pair gives one before-and-after rule, from its first different letter. Order the rules with a topological sort.
- Time
- O(c)
- Space
- O(1)
Also works with Graphs.