Skip to the solution
HardDSA10 min read

What is the difference between Kruskal's and Prim's MST algorithms?

696 views

The problem

Question presented to candidate: "Both Kruskal's and Prim's algorithms find a minimum spanning tree. How does each one work, why are both correct, and which would you pick for a given graph? Please implement both in Python."

What a strong answer should cover:

  • The goal: a minimum spanning tree connects all V vertices with V - 1 edges of minimum total weight, for a connected, undirected, weighted graph.
  • Kruskal is edge-first: sort all edges, take each one that joins two different components (checked with union-find), O(E log E).
  • Prim is vertex-first: grow one tree from a start vertex, always adding the cheapest edge that leaves it, using a min-heap, O(E log V); an O(V²) array version suits dense graphs.
  • Why both are correct: the cut property (the cheapest edge across any cut is safe); and the practical differences: sparse vs dense, edge list vs adjacency list, a spanning forest for disconnected graphs (Kruskal) vs one component (Prim).
  • Python specifics: sorted(edges, key=...) for Kruskal, heapq (a min-heap) of (weight, vertex, from) tuples for Prim, and the tie trap: tuples compare element by element, so a non-comparable payload in a tuple raises TypeError on equal weights.

Clarifying questions expected:

  • "Is the graph connected, and if not, do you want a spanning forest?"
  • "How is the graph given: an edge list or an adjacency list? Roughly how many edges per vertex?"

Code / implementation expected: Yes — both in Python: Kruskal with a small union-find, and lazy Prim with heapq.

  • graphs
  • mst

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read · 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonKruskal and Prim traced on the same graph, plus a disconnected graph
PythonThree MST algorithms agree; their work on sparse vs dense graphs

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 143 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextHard

What is a segment tree and when do you need one?

Continue