Min Cost to Connect All Points

Difficulty: Medium

You're given points on a 2D plane, where points[i] = [xi, yi]. Connecting two points costs their Manhattan distance: |xi - xj| + |yi - yj|.

Find the minimum total cost to connect all the points, so there's some path (possibly through other points) between every pair.

Examples

Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
Output: 20

One cheapest way connects the points in a tree using edges totaling 20, rather than paying for every possible pairwise connection.

Input: points = [[3,12],[-2,5],[-4,1]]
Output: 18

Connecting (-4,1)-(-2,5) costs 6, and (-2,5)-(3,12) costs 12, for a total of 18 - cheaper than any other way to link all three points.

Input: points = [[0,0],[1,1],[1,0],[0,1]]
Output: 3

These four points form a unit square where every side (but not the diagonals) costs 1 to connect; a spanning tree needs only 3 of those unit-cost sides, for a total of 3.

Constraints

  • 1 <= points.length <= 1000

  • -10^6 <= xi, yi <= 10^6

  • All pairs of points are distinct.

Approach

This asks for a Minimum Spanning Tree (MST): the cheapest set of connections linking every point into one group. For n points it uses exactly n - 1 connections (every cycle-free spanning tree does).

Every pair of points can connect directly, so it's an MST over a complete graph with Manhattan distances as edge weights.

Two classic algorithms apply:

  • Kruskal's builds all n * (n - 1) / 2 edges, sorts them by cost, and adds each one unless it would form a cycle (checked with union-find), until all points connect.
  • Prim's grows one tree from a start point, always adding the cheapest edge from the tree to a point outside it. It never builds the full edge list, which matters more as n grows.

Solutions

Kruskal's Algorithm - Sort Edges + Union-Find

Build every edge between pairs of points with its Manhattan cost, and sort them from cheapest to most expensive. Add each edge to the tree unless its endpoints are already connected (it would create a useless cycle). A union-find (disjoint set) structure answers "already connected?" and merges groups quickly. Stop after n - 1 edges - the tree spans every point.

function minCostConnectPoints(points) {
  const n = points.length;
  const edges = [];
  for (let i = 0; i < n; i++) {
    for (let j = i + 1; j < n; j++) {
      const cost = Math.abs(points[i][0] - points[j][0]) + Math.abs(points[i][1] - points[j][1]);
      edges.push([cost, i, j]);
    }
  }
  edges.sort((a, b) => a[0] - b[0]);

  const parent = Array.from({ length: n }, (_, i) => i);
  function find(x) {
    while (parent[x] !== x) {
      parent[x] = parent[parent[x]];
      x = parent[x];
    }
    return x;
  }

  let totalCost = 0;
  let edgesUsed = 0;
  for (const [cost, i, j] of edges) {
    const rootI = find(i);
    const rootJ = find(j);
    if (rootI === rootJ) continue;
    parent[rootI] = rootJ;
    totalCost += cost;
    edgesUsed++;
    if (edgesUsed === n - 1) break;
  }

  return totalCost;
}

Time: O(n^2 log n), dominated by sorting the O(n^2) candidate edges · Space: O(n^2) to store every candidate edge

Optimal - Prim's Algorithm

Start the tree with one point. An array minCost holds, for each point outside the tree, the cheapest known cost to connect it to some point in the tree (infinity at first, except the start point).

Repeatedly pick the outside point with the smallest minCost, add it to the tree and its cost to the total, then update minCost for the remaining points using their distance to the new point. After n points, the total is the MST cost. The full O(n^2) edge list is never built or sorted.

function minCostConnectPoints(points) {
  const n = points.length;
  const inTree = new Array(n).fill(false);
  const minCost = new Array(n).fill(Infinity);
  minCost[0] = 0;

  let totalCost = 0;

  for (let added = 0; added < n; added++) {
    let u = -1;
    for (let i = 0; i < n; i++) {
      if (!inTree[i] && (u === -1 || minCost[i] < minCost[u])) {
        u = i;
      }
    }

    inTree[u] = true;
    totalCost += minCost[u];

    for (let v = 0; v < n; v++) {
      if (inTree[v]) continue;
      const cost = Math.abs(points[u][0] - points[v][0]) + Math.abs(points[u][1] - points[v][1]);
      if (cost < minCost[v]) {
        minCost[v] = cost;
      }
    }
  }

  return totalCost;
}

Time: O(n^2), since each of the n rounds scans all n points to pick the next one and to update costs · Space: O(n) for the minCost and inTree arrays