week 12 of 15
Graphs II: union-find and shortest paths
Get comfortable with these coding mechanics first: a union-find class (find with path compression, union), a heap of (distance, node), weighted adjacency lists. Template to type from memory by the end of the week: dijkstra: heap of (dist, node). Pop. Skip if stale. Relax each edge and push improvements.
- 98Redundant Connection (opens LeetCode in a new tab)Union-findMedium
- Common mistake
- Forgetting to initialise parent[i] = i, or to compress paths.
- 99Accounts Merge (opens LeetCode in a new tab)Union-find over stringsMedium
- Common mistake
- Mapping emails to ids inconsistently.
- 100Word Ladder (opens LeetCode in a new tab)BFS shortest path (hard)Hard
- Common mistake
- Counting edges instead of words. The answer counts words in the path.
- 101Network Delay Time (opens LeetCode in a new tab)DijkstraMedium
- Common mistake
- Not skipping stale entries, and forgetting unreachable nodes.
- 102Cheapest Flights Within K Stops (opens LeetCode in a new tab)Bellman-Ford with a limitMedium
- Common mistake
- Relaxing in place, which allows more than k stops.
- 103Min Cost to Connect All Points (opens LeetCode in a new tab)Minimum spanning treeMedium
- Common mistake
- Building the edge list carelessly. There are n(n-1)/2 edges.
- 104Alien Dictionary (opens LeetCode in a new tab)Topological sort on a derived graphHard
- Common mistake
- Invalid case: a longer word before its own prefix. Also detect cycles.