STOP 18 · GRAPHS
Spanning Trees and Tree Graphs
Kruskal: sort the edges, join with union-find O(E log E)
- Learn first
- Leads to
- No later stop builds on it.
- How often asked
- No interview reports map onto this stop yet.
Warm up with this one
LC 1584Min Cost to Connect All PointsStuck? Peek at the approach
Model point-connection costs as a weighted graph and use a minimum spanning tree to avoid incorrect local greedy choices.
Key points
- Go through the edges from lightest to heaviest; take an edge if it joins two different components, otherwise skip it (it would close a cycle).
- n-1 chosen edges form a spanning tree; fewer than that means the graph is disconnected.
- On dense graphs such as all pairs of points, the O(n²) form of Prim is often faster than sorting every edge.
Common pitfalls
- Returning the summed weight without checking that every node got connected.
- All pairs of points give n²/2 edges, which can exceed both the memory and the time limit for sorting.
- Nodes numbered from 1 overflow a union-find sized n by one.
Watch it run
Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.
Kruskal · minimum spanning tree
Connect all 6 nodes with the least total weight
- Edges taken
- 0 / 5
- Total weight
- 0
The edges are sorted by weight (the cells below). At first every node is its own component.
InvariantThe chosen edges never form a cycle; in weight order, take the lightest edge that joins two different components.
Template
Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 1584, with it.
Python
def mst_weight(n: int, edges: list[tuple[int, int, int]]) -> int:
"""Undirected edges (u, v, w). Weight of a minimum spanning tree, or -1 if disconnected."""
parent = list(range(n))
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
total = used = 0
for u, v, w in sorted(edges, key=lambda e: e[2]):
ru, rv = find(u), find(v)
if ru != rv: # the lightest edge joining two different components
parent[ru] = rv
total += w
used += 1
return total if used == n - 1 else -1C++
// Undirected edges {u, v, w}. Weight of a minimum spanning tree, or -1 if disconnected.
long long mstWeight(int n, vector<array<int, 3>> edges) {
sort(edges.begin(), edges.end(), [](auto& a, auto& b) { return a[2] < b[2]; });
vector<int> parent(n);
iota(parent.begin(), parent.end(), 0);
auto find = [&](int x) {
while (parent[x] != x) x = parent[x] = parent[parent[x]];
return x;
};
long long total = 0;
int used = 0;
for (auto& [u, v, w] : edges) {
int ru = find(u), rv = find(v);
if (ru == rv) continue; // would close a cycle
parent[ru] = rv;
total += w;
used++;
}
return used == n - 1 ? total : -1;
}Java
class Solution {
private int[] parent;
// Undirected edges {u, v, w}. Weight of a minimum spanning tree, or -1 if disconnected.
long mstWeight(int n, int[][] edges) {
Arrays.sort(edges, (a, b) -> Integer.compare(a[2], b[2]));
parent = new int[n];
for (int i = 0; i < n; i++) parent[i] = i;
long total = 0;
int used = 0;
for (int[] e : edges) {
int ru = find(e[0]), rv = find(e[1]);
if (ru == rv) continue; // would close a cycle
parent[ru] = rv;
total += e[2];
used++;
}
return used == n - 1 ? total : -1;
}
private int find(int x) {
while (parent[x] != x) x = parent[x] = parent[parent[x]];
return x;
}
}Go
import "sort"
// mstWeight takes undirected edges {u, v, w} and returns the weight of a minimum
// spanning tree, or -1 if the graph is disconnected.
func mstWeight(n int, edges [][3]int) int {
sort.Slice(edges, func(i, j int) bool { return edges[i][2] < edges[j][2] })
parent := make([]int, n)
for i := range parent {
parent[i] = i
}
find := func(x int) int {
for parent[x] != x {
parent[x] = parent[parent[x]]
x = parent[x]
}
return x
}
total, used := 0, 0
for _, e := range edges {
ru, rv := find(e[0]), find(e[1])
if ru == rv {
continue // would close a cycle
}
parent[ru] = rv
total += e[2]
used++
}
if used != n-1 {
return -1
}
return total
}Common variants
Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.
Prim on a dense graph: O(n²), no heapO(n²) time · O(n) space
On a complete graph, or one with close to n² edges (LC 1584, Min Cost to Connect All Points), listing every edge and sorting it for Kruskal costs O(n² log n). Prim adds the nearest outside node each round and updates the others' distances from it; with a plain array scan that is O(n²) and stores no edges.
Python
def min_cost_connect(points: list[list[int]]) -> int:
"""Minimum spanning tree weight of all points under Manhattan distance (LC 1584)."""
n = len(points)
dist = [float("inf")] * n # dist[v]: cheapest edge from the tree to v so far
dist[0] = 0
in_tree = [False] * n
total = 0
for _ in range(n):
u = min((v for v in range(n) if not in_tree[v]), key=lambda v: dist[v]) # nearest outside node
in_tree[u] = True
total += dist[u]
for v in range(n):
if not in_tree[v]:
d = abs(points[u][0] - points[v][0]) + abs(points[u][1] - points[v][1])
dist[v] = min(dist[v], d)
return totalC++
// Minimum spanning tree weight of all points under Manhattan distance (LC 1584).
long long minCostConnect(const vector<pair<int, int>>& points) {
int n = points.size();
vector<long long> dist(n, LLONG_MAX); // dist[v]: cheapest edge from the tree to v so far
dist[0] = 0;
vector<bool> inTree(n, false);
long long total = 0;
for (int round = 0; round < n; round++) {
int u = -1;
for (int v = 0; v < n; v++) // nearest outside node
if (!inTree[v] && (u < 0 || dist[v] < dist[u])) u = v;
inTree[u] = true;
total += dist[u];
for (int v = 0; v < n; v++)
if (!inTree[v]) {
long long d = abs(points[u].first - points[v].first) + abs(points[u].second - points[v].second);
dist[v] = min(dist[v], d);
}
}
return total;
}Java
class Solution {
// Minimum spanning tree weight of all points under Manhattan distance (LC 1584).
long minCostConnect(int[][] points) {
int n = points.length;
long[] dist = new long[n]; // dist[v]: cheapest edge from the tree to v so far
Arrays.fill(dist, Long.MAX_VALUE);
dist[0] = 0;
boolean[] inTree = new boolean[n];
long total = 0;
for (int round = 0; round < n; round++) {
int u = -1;
for (int v = 0; v < n; v++) // nearest outside node
if (!inTree[v] && (u < 0 || dist[v] < dist[u])) u = v;
inTree[u] = true;
total += dist[u];
for (int v = 0; v < n; v++)
if (!inTree[v]) {
long d = Math.abs(points[u][0] - points[v][0]) + Math.abs(points[u][1] - points[v][1]);
dist[v] = Math.min(dist[v], d);
}
}
return total;
}
}Go
// minCostConnect returns the minimum spanning tree weight of all points under Manhattan distance.
func minCostConnect(points [][2]int) int {
n := len(points)
abs := func(x int) int {
if x < 0 {
return -x
}
return x
}
dist := make([]int, n) // dist[v]: cheapest edge from the tree to v so far
for v := 1; v < n; v++ {
dist[v] = 1 << 62
}
inTree := make([]bool, n)
total := 0
for round := 0; round < n; round++ {
u := -1
for v := 0; v < n; v++ { // nearest outside node
if !inTree[v] && (u < 0 || dist[v] < dist[u]) {
u = v
}
}
inTree[u] = true
total += dist[u]
for v := 0; v < n; v++ {
if !inTree[v] {
d := abs(points[u][0]-points[v][0]) + abs(points[u][1]-points[v][1])
dist[v] = min(dist[v], d)
}
}
}
return total
}Peel leaves layer by layer to find the centreO(n) time · O(n) space
To find the roots that make a tree shortest (LC 310, Minimum Height Trees): peel the degree-1 leaves off layer by layer, much like a topological sort, and the last one or two nodes left are the centres. Each node enters and leaves once, O(n), instead of a BFS from every node.
Python
def min_height_roots(n: int, edges: list[list[int]]) -> list[int]:
"""Roots giving the tree its minimum height (LC 310): the 1 or 2 nodes left after peeling leaves."""
if n <= 2:
return list(range(n))
graph = [[] for _ in range(n)]
deg = [0] * n
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
deg[u] += 1
deg[v] += 1
leaves = [u for u in range(n) if deg[u] == 1]
left = n
while left > 2: # peel one whole layer of leaves at a time
left -= len(leaves)
nxt = []
for leaf in leaves:
for nb in graph[leaf]:
deg[nb] -= 1
if deg[nb] == 1: # nb just became a leaf of the smaller tree
nxt.append(nb)
leaves = nxt
return sorted(leaves)C++
// Roots giving the tree its minimum height (LC 310): the 1 or 2 nodes left after peeling leaves.
vector<int> minHeightRoots(int n, const vector<pair<int, int>>& edges) {
if (n <= 2) {
vector<int> all(n);
iota(all.begin(), all.end(), 0);
return all;
}
vector<vector<int>> graph(n);
vector<int> deg(n, 0), leaves;
for (auto [u, v] : edges) {
graph[u].push_back(v);
graph[v].push_back(u);
deg[u]++;
deg[v]++;
}
for (int u = 0; u < n; u++)
if (deg[u] == 1) leaves.push_back(u);
for (int left = n; left > 2;) { // peel one whole layer of leaves at a time
left -= leaves.size();
vector<int> next;
for (int leaf : leaves)
for (int nb : graph[leaf])
if (--deg[nb] == 1) next.push_back(nb); // nb just became a leaf of the smaller tree
leaves = next;
}
sort(leaves.begin(), leaves.end());
return leaves;
}Java
class Solution {
// Roots giving the tree its minimum height (LC 310): the 1 or 2 nodes left after peeling leaves.
List<Integer> minHeightRoots(int n, int[][] edges) {
List<Integer> leaves = new ArrayList<>();
if (n <= 2) {
for (int u = 0; u < n; u++) leaves.add(u);
return leaves;
}
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) graph.add(new ArrayList<>());
int[] deg = new int[n];
for (int[] e : edges) {
graph.get(e[0]).add(e[1]);
graph.get(e[1]).add(e[0]);
deg[e[0]]++;
deg[e[1]]++;
}
for (int u = 0; u < n; u++)
if (deg[u] == 1) leaves.add(u);
for (int left = n; left > 2;) { // peel one whole layer of leaves at a time
left -= leaves.size();
List<Integer> next = new ArrayList<>();
for (int leaf : leaves)
for (int nb : graph.get(leaf))
if (--deg[nb] == 1) next.add(nb); // nb just became a leaf of the smaller tree
leaves = next;
}
Collections.sort(leaves);
return leaves;
}
}Go
import "sort"
// minHeightRoots returns the roots giving the tree its minimum height (LC 310).
func minHeightRoots(n int, edges [][2]int) []int {
if n <= 2 {
all := make([]int, n)
for i := range all {
all[i] = i
}
return all
}
graph := make([][]int, n)
deg := make([]int, n)
for _, e := range edges {
graph[e[0]] = append(graph[e[0]], e[1])
graph[e[1]] = append(graph[e[1]], e[0])
deg[e[0]]++
deg[e[1]]++
}
var leaves []int
for u := 0; u < n; u++ {
if deg[u] == 1 {
leaves = append(leaves, u)
}
}
for left := n; left > 2; { // peel one whole layer of leaves at a time
left -= len(leaves)
var next []int
for _, leaf := range leaves {
for _, nb := range graph[leaf] {
deg[nb]--
if deg[nb] == 1 { // nb just became a leaf of the smaller tree
next = append(next, nb)
}
}
}
leaves = next
}
sort.Ints(leaves)
return leaves
}Why it works
- Cut property: for any split of the nodes into two sides, the lightest edge crossing the split belongs to some minimum spanning tree. If a tree lacks it, adding it closes a cycle with another crossing edge, and swapping that one out cannot make the tree heavier.
- Each edge Kruskal accepts is the lightest edge joining two different components, which makes it the lightest edge across the cut between one of those components and everything else, so every step is safe. An edge inside one component would close a cycle and is never needed.
Say it in 30 seconds
When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.
最小生成树我用 Kruskal:边按权重从小到大排序,用并查集判断两端是否已连通,不连通就选上,连通就跳过,因为它会成环。正确性来自切割性质:每次选的边都是某个切割上最轻的横跨边,一定出现在某棵最小生成树里。选满 n−1 条就是生成树,不够说明图不连通。复杂度主要是排序,O(E log E)。For a minimum spanning tree I use Kruskal: sort the edges by weight, and take each edge whose endpoints union-find says are not yet connected, skipping the ones that would close a cycle. It is correct by the cut property: every accepted edge is the lightest edge across some cut, so it belongs to some minimum spanning tree. With n minus one edges chosen I have a spanning tree, and fewer means the graph is disconnected. Sorting dominates, so it is O(E log E).Grade yourself
Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.
Quick quiz
3 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice
Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.
Template drills
Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.
These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.
def mst_weight(n: int, edges: list[tuple[int, int, int]]) -> int:
"""Undirected edges (u, v, w). Weight of a minimum spanning tree, or -1 if disconnected."""
parent = list(range(n))
return total if used == n - 1 else -1Practice by stage
This stop's 3 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.
Core 2
| # | Problem | Approach | Rating |
|---|---|---|---|
| 1584 | Min Cost to Connect All Points | Model point-connection costs as a weighted graph and use a minimum spanning tree to avoid incorrect local greedy choices. | |
| 310 | Minimum Height Trees | Peel leaves layer by layer to locate tree centers instead of recomputing height from every node. |
Advanced 1
| # | Problem | Approach | Rating |
|---|---|---|---|
| 1168 | Optimize Water Distribution in a Village 🔒 | Add a virtual water-source node to model both wells and pipes in one minimum spanning tree. |
OA questions on this topic 3
- Minimize Path ValueSalesforce
- Minimize Path ValuePalantir
- Min Cost to Connect All PointsNutanix
Core Skills
Build this stop's data structure or algorithm by hand, without libraries, judged in four languages.