Unit 7 of 9 · about 4 hours · derive, implement

Minimum spanning trees with Kruskal and Prim

Minimum connection cost is the canonical greedy-with-proof: one theorem justifies two algorithms, and the input shape picks between them.

You'll be able to

  • Implement Kruskal with sorted edges plus union-find and lazy Prim with a frontier heap, stating each stale-entry rule.
  • Prove accepted edges are safe with the cut-property exchange argument, and rejected edges with the cycle property.
  • Choose Kruskal for explicit edge lists and Prim (dense or heap) for dense or implicit graphs.

Covers

Minimum spanning trees with Kruskal and Prim
1

Read

In this order, only the parts listed

0 of 3 done

  1. Minimum spanning tree: Kruskal's algorithmDSA Handbook - graphs

    The pattern (LC 1584); Why it works: the cut property; Worked example on the canonical 7-vertex graph (weight 31); Variants: virtual source node

    Skim LC 1489's Kruskal-twice-per-edge on first pass; edge classification is stretch.

  2. Minimum spanning trees: Prim's algorithmDSA Handbook - graphs

    The pattern with the in_mst skip; When the graph is implicit: LC 1584; Dense Prim from to ; Kruskal vs Prim: the decision table

  3. Minimum Spanning Trees, Chapter 7Algorithms - graph chapters

    7.1 Distinct Edge Weights; 7.2 The Only Minimum Spanning Tree Algorithm (safe and useless edges); 7.3 Boruvka's Algorithm; 7.4 Jarnik's ("Prim's") Algorithm; 7.5 Kruskal's Algorithm (printed pp. 257-268)

2

Focus on

  • Kruskal's guard is union: accept iff endpoints sit in different components, stop at edges. The sort dominates at ; the DSU loop is effectively linear.
  • Lazy Prim pushes (weight, vertex) pairs and skips with if in_mst[u]: continue. The heap holds duplicates; the eager decrease-key variant needs an indexed heap no standard library ships.
  • Prim cumulates nothing: pushing distance-from-start plus edge weight builds a shortest-path tree, not an MST. Dijkstra cumulates, Prim does not.
  • Every MST has the same total weight, and distinct weights also make the edge set unique. With ties, as in LC 1584, Kruskal and Prim may pick different edges but must report the same total.
Common mistakes · 3
  • Early break on disconnected input: stopping is valid only when accepts happen. Otherwise walk every edge and return -1 when accepts fall short.
  • Integer totals in Java and C++: LC 1584 edge weights reach and 999 of them sum past INT_MAX. Accumulate in long or long long; Python integers are exempt.
  • Forgetting either DSU heuristic: one-sided chains push finds to before compression ever fires. Ship path halving with union by rank as in the handbook reference.
3

Try it yourself

Closed-book, before checking anything

From a blank file with the course Python (3.13.14), run Kruskal and dense Prim on [[0,0],[2,2],[3,10],[5,2],[7,0]]; both return 20. State the input size (, complete graph of 10 Manhattan edges) and which variant each function is.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Prove the cut property by exchange.Answer

    Let be the lightest edge across cut and an MST missing . Adding creates a cycle with another crossing edge of weight at least . Swapping for keeps a spanning tree of no greater weight, so some MST contains .

  2. 2.Why is a rejected Kruskal edge safe to drop?Answer

    Its endpoints already connect through accepted edges, each processed earlier hence no heavier. The closed cycle's other edges are all at most as heavy, so the rejected edge is a heaviest edge of that cycle and no MST needs it.

  3. 3.Why does dense Prim beat heap Prim on LC 1584?Answer

    The complete graph materializes about 500,000 edges at ; heap Prim pays on them while dense Prim scans min_edge arrays for with no heap and no stale entries.

  4. 4.Kruskal and Prim report different totals on the same input. What follows?Answer

    A bug: all minimum spanning trees share one total weight, so two correct runs agree on it even when tied weights let them choose different edges. Check the stale skip, the union guard and the weight function.

5

Practice

  • LeetCode 1584: Min Cost to Connect All Points

    The five-point example (answer 20) and the two-point example

    Implement both Kruskal and Prim in one file and assert equal totals. Manhattan weights tie, so the chosen edges may differ, but a different total means a bug. After-attempt reference is DSA Handbook 8.11 and 8.12.

You're done when

Your blank-file script prints 20 from both functions on the five-point input, and you can state the Kruskal-versus-Prim choice for an edge list, a dense matrix and a point set without hedging.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 3 more in the section
  • DSA Handbook - graphsHandbook Academy · primary

    Study all of Part 8 in order. For each algorithm, write the representation, invariant, forbidden input assumptions and independently checkable output before reading the implementation.

  • Algorithms - graph chaptersJeff Erickson · required

    Use the basic graph, depth-first search, minimum spanning tree, shortest path and flow chapters, and lecture note 11 Disjoint Sets for union-find, for correctness proofs and counterexamples to tempting wrong algorithms.

Also in this section

  • AlgoMaster DSA - graph sliceAlgoMaster · required

    Attempt Number of Islands, Course Schedule II and Network Delay Time cold. They cover traversal, dependency modeling and weighted shortest paths; add one narrative problem only if graph modeling remains weak.

  • Hypothesis - generated graph testsHypothesis · support

    Generate small sparse, dense, disconnected, cyclic, parallel-edge and weighted graphs. Compare optimized results with exhaustive or deliberately simple references and retain shrunk failures.

  • NeetCode - unseen graph problemsNeetCode · optional

    Use two unseen story problems without graph tags. Grade the model, assumptions, certificate and tests as well as the final answer.