Skip to content
DSA Patterns
Menu
Language
Minimum Spanning TreeLC #15844 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Min Cost to Connect All Points

Problem (restated)

Points on the plane. Cost of an edge is Manhattan |x1-x2| + |y1-y2|. Return the MST weight connecting all points.

Intuition

Complete graph, n ≤ 1000 so n² edges are fine. Generate every pair, Kruskal.

Approaches

Kruskal, Manhattan

Unverified
Time O(n² log n)Space O(n²)

Idea. For i < j, push (i, j, manhattan). Sort, union until n-1 edges.

Walkthrough. [[0,0],[2,2],[3,10],[5,2],[7,0]] → 20.

Trade-offs. Prim from one seed with a dense O(n²) scan avoids storing all edges; Kruskal is the template and is simpler. Points are 0-indexed.

Solution
export function minCostConnectPoints(points: number[][]): number {
  const n = points.length;
  const edges: [number, number, number][] = [];
  for (let i = 0; i < n; i++) {
    for (let j = i + 1; j < n; j++) {
      const w = Math.abs(points[i]![0]! - points[j]![0]!) + Math.abs(points[i]![1]! - points[j]![1]!);
      edges.push([i, j, w]);
    }
  }
  edges.sort((a, b) => a[2] - b[2]);
  const parent = Array.from({ length: n }, (_, i) => i);
  const size = new Array<number>(n).fill(1);
  const find = (x: number): number => {
    while (parent[x]! !== x) {
      parent[x] = parent[parent[x]!]!; // path halving keeps the tree shallow, iteratively
      x = parent[x]!;
    }
    return x;
  };
  let cost = 0, used = 0;
  for (const [u, v, w] of edges) {
    let a = find(u), b = find(v);
    if (a === b) continue;
    if (size[a]! < size[b]!) { const t = a; a = b; b = t; }
    parent[b] = a;
    size[a] = size[a]! + size[b]!;
    cost += w;
    used++;
    if (used === n - 1) break;
  }
  return cost;
}
export function minCostConnectPoints(points: number[][]): number {
  const n = points.length;
  const edges: [number, number, number][] = [];
  for (let i = 0; i < n; i++) {
    for (let j = i + 1; j < n; j++) {
      const w = Math.abs(points[i]![0]! - points[j]![0]!) + Math.abs(points[i]![1]! - points[j]![1]!);
      edges.push([i, j, w]);
    }
  }
  edges.sort((a, b) => a[2] - b[2]);
  const parent = Array.from({ length: n }, (_, i) => i);
  const size = new Array<number>(n).fill(1);
  const find = (x: number): number => {
    while (parent[x]! !== x) {
      parent[x] = parent[parent[x]!]!; // path halving keeps the tree shallow, iteratively
      x = parent[x]!;
    }
    return x;
  };
  let cost = 0, used = 0;
  for (const [u, v, w] of edges) {
    let a = find(u), b = find(v);
    if (a === b) continue;
    if (size[a]! < size[b]!) { const t = a; a = b; b = t; }
    parent[b] = a;
    size[a] = size[a]! + size[b]!;
    cost += w;
    used++;
    if (used === n - 1) break;
  }
  return cost;
}

Template connection

Kruskal after you materialize the complete graph. Same as LC 1135 with a generated edge list.

Reflection

  • The cost is Manhattan. Every pair is an edge. Kruskal keeps n - 1 of them. Prim reaches the same total.
  • n = 1 answers 0. Two equal points cost 0. A negative coordinate is fine because the distance uses the absolute value.
  • There are on the order of n**2 edges. The sort decides which costs win. An edge that closes a cycle is skipped.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 7
1/7

Connect all nodes at minimum total weight. Edges: AB1, BC2, AC3, BD4, CD5. MST ≠ shortest path.

13245ABCD
Stateedges=AB:1, BC:2, AC:3, BD:4, CD:5

Kruskal: sort edges, skip cycles

Key:CurrentActive rangeMatchSettled