🚀 Phases 1–5 are live — Days 1–17 cover the foundations and the algorithmic patterns. See the roadmap →

Basic MST Questions

Six warm-ups. The first three exercises build the data structures you’ll rely on in all MST problems; the last three are direct algorithm applications.

1. Union-Find from scratch

Implement a Union-Find (disjoint-set) data structure with path compression and union by rank. Support find(x) and unite(x, y).

This is the backbone of Kruskal’s algorithm. Write it from memory before every MST problem.

Time: find and unite both run in O(α(n)) ≈ O(1). Space: O(n).

2. Count connected components

Given n nodes and a list of edges, return the number of connected components.

Time: O(E α(V)) ≈ O(E). Space: O(V).

3. Detect cycle in undirected graph

Given an undirected graph, return true if it contains a cycle.

With Union-Find: adding an edge (u, v) creates a cycle iff find(u) == find(v).

Time: O(E α(V)). Same as Union-Find operations.

4. Manual Kruskal trace

Trace Kruskal’s on the graph: 4 nodes, edges {(A,B,3), (A,C,1), (B,C,4), (B,D,2), (C,D,5)}. Write the MST edges in order added.

Work through it:

  1. Sort: (A,C,1), (B,D,2), (A,B,3), (B,C,4), (C,D,5)
  2. Add (A,C,1) — no cycle. MST: [AC]
  3. Add (B,D,2) — no cycle (B and D disconnected). MST: [AC, BD]
  4. Add (A,B,3) — A is in component [A,C], B is in [B,D] — no cycle. MST: [AC, BD, AB]
  5. (B,C,4) — B and C now connected via A. Skip.
  6. (C,D,5) — C and D now connected via A-B-D. Skip.

MST: [AC, BD, AB], total weight = 1 + 2 + 3 = 6.

edges = [(1,"A","C"),(2,"B","D"),(3,"A","B"),(4,"B","C"),(5,"C","D")]
# After Kruskal's: total = 6

5. MST minimum cost

Implement a complete mst_cost(n, edges) function that returns the minimum spanning tree weight, or -1 if the graph is not connected.

Test cases:

# Connected graph
mst_cost(4, [[0,1,1],[0,2,4],[1,2,2],[1,3,6],[2,3,3]])  # → 1+2+3 = 6
 
# Disconnected graph
mst_cost(3, [[0,1,1]])  # → -1 (node 2 unreachable)

6. Check if adding an edge would create a cycle

Given a partially built spanning tree (list of edges) and a new edge (u, v), determine if adding (u, v) would create a cycle. O(V) time.

Simple Union-Find application: build the union-find from existing edges, then check find(u) == find(v).

This is exactly the check Kruskal’s performs for each candidate edge.

Mini-quiz

Path compression in Union-Find's 'find' makes each subsequent find faster. What does 'path compression' actually do?
After running Kruskal's on a disconnected graph with k components, what does the result look like?

Next: the eight practice problems — every MST technique from the chapter applied to classic interview questions.