knaxuslearn · build · ship

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.

  1. 98Redundant Connection (opens LeetCode in a new tab)Union-findMedium
    Common mistake
    Forgetting to initialise parent[i] = i, or to compress paths.
  2. 99Accounts Merge (opens LeetCode in a new tab)Union-find over stringsMedium
    Common mistake
    Mapping emails to ids inconsistently.
  3. 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.
  4. 101Network Delay Time (opens LeetCode in a new tab)DijkstraMedium
    Common mistake
    Not skipping stale entries, and forgetting unreachable nodes.
  5. 102Cheapest Flights Within K Stops (opens LeetCode in a new tab)Bellman-Ford with a limitMediumcore
    Common mistake
    Relaxing in place, which allows more than k stops.
  6. 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.
  7. 104Alien Dictionary (opens LeetCode in a new tab)Topological sort on a derived graphHardcorePremium
    Common mistake
    Invalid case: a longer word before its own prefix. Also detect cycles.