hardDSA

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

695 views
01

Understand the problem

Compare the two MST algorithms.

graphsmst
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

Kruskal's MST (Union-Find)
Run Playground
def kruskal_mst(n, edges):
    parent = list(range(n))
    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x
    total, used = 0, 0
    for w, u, v in sorted(edges):           # cheapest edge first
        ru, rv = find(u), find(v)
        if ru != rv:                        # skip if it would form a cycle
            parent[ru] = rv
            total += w
            used += 1
    return total if used == n - 1 else -1   # -1 = graph not connected


# --- demo ---  edges (w, u, v)
edges = [(10, 0, 1), (6, 0, 2), (5, 0, 3), (15, 1, 3), (4, 2, 3)]
print(kruskal_mst(4, edges))   # 19  (edges 4 + 5 + 10)
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.