InterviewPrepKit

Home / Coding / Advanced Graphs

Min Cost to Connect All Points

medium Original ↗
Solving tips
  • 'Connect everything at minimum total cost' with no path-length requirement is a minimum spanning tree, not shortest path.
  • The graph is complete/dense (~n^2/2 edges), so prefer array-based Prim's at O(n^2) over heap Prim or Kruskal's O(n^2 log n) sort.
  • Array Prim: keep min_edge[v] = cheapest cost to the growing tree, scan for the min, absorb it, then update the array; no heap or edge list needed.
  • Watch the distance metric (Manhattan, not Euclidean) and the n==1 base case (cost 0).

Problem

You are given n points on a 2D plane, points[i] = [x_i, y_i], all distinct. Connecting two points costs their Manhattan distance: |x_i - x_j| + |y_i - y_j|.

Return the minimum total cost to wire the points together so that every point can reach every other point through some chain of connections. Any pair may be connected directly; you choose which pairs.

In graph terms: the points form a complete weighted graph, and you must pick the cheapest subset of edges that keeps it connected — a minimum spanning tree.

Examples

  • points = [[0,0],[2,2],[3,10],[5,2],[7,0]]20 — connect (0,0)–(2,2) for 4, (2,2)–(5,2) for 3, (5,2)–(7,0) for 4, (2,2)–(3,10) for 9.
  • points = [[3,12],[-2,5],[-4,1]]18 — (-4,1)–(-2,5) costs 6, (-2,5)–(3,12) costs 12.
  • points = [[0,0]]0 — a single point needs no wires.

Constraints

  • 1 <= n <= 1000
  • -10^6 <= x_i, y_i <= 10^6
  • All points are distinct.

Note the graph is complete: about n^2 / 2 ≈ 500,000 candidate edges at the top end.

Think about it first

Hint 1 Connecting all points with minimum total edge weight and no benefit from cycles — this is the textbook definition of a minimum spanning tree. A tree on n points has exactly n - 1 edges.
Hint 2 Kruskal's approach: sort all pairwise edges by cost and greedily take each edge that joins two different components (union-find detects that). Works, but sorting ~500k edges is the dominant cost.
Hint 3 Because the graph is complete (dense), Prim's algorithm with a plain array beats heap-based methods: keep, for every point not yet in the tree, its cheapest connection to the tree; repeat n times "absorb the cheapest outside point, then update the array". That's O(n^2) with no sorting and no heap.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.