Min Cost to Connect All Points solution explained

Min Cost to Connect All Points asks for the cheapest way to link every point on a grid when joining two points costs their Manhattan distance, |x1 - x2| + |y1 - y2|. That is a minimum spanning tree on a complete graph. Prim's algorithm with a plain distance array grows the tree one point at a time in O(n²) time and O(n) space, which beats sorting all n² edges for Kruskal's algorithm on a graph this dense.

By Published 8 min read

The task, restated

A campus has a set of buildings at integer grid positions, and cable can only run along the street grid, so linking two buildings costs the horizontal gap plus the vertical gap between them. You may link any pair directly. Find the smallest total cable length that leaves every building connected to every other, directly or through other buildings. One building needs no cable.

Examples made up for this page
PointsMinimum totalLinks used
(0,0) (3,1) (1,4) (6,6) (5,0)19(3,1)-(5,0) 3, (0,0)-(3,1) 4, (0,0)-(1,4) 5, (1,4)-(6,6) 7
(1,1) (4,5)7The only link: 3 across plus 4 up
(-2,3) (1,-1) (4,4) (0,0)14Three links; negative coordinates are fine
(0,0) (0,0) (2,0)2The two copies link for free
(2,2)0Nothing to connect
Examples made up for this page. Scroll sideways on a small screen.

Worth asking: can points repeat, how many points can there be, and how large are the coordinates? Repeats are harmless, a few thousand points is comfortable for an O(n²) method, and coordinates in the millions keep sums well within ordinary integer ranges.

What the interviewer is checking

The problem never says spanning tree. The first thing graded is whether you recognize it: a set of nodes, a cost per link, and a demand that everything be connected at least cost. The second is choosing an algorithm that fits a complete graph. Kruskal is the version many people learn first, and it works, but generating and sorting every edge wastes time and memory when Prim with a simple array does the job in O(n²) with no heap at all. Explaining that trade-off is what separates a good answer from a correct one.

Why a greedy choice is safe here

Both algorithms are greedy, and both rest on the cut property: if you split the points into two groups, the cheapest link crossing between the groups belongs to some minimum spanning tree. Prim keeps one group as the tree built so far and always adds the cheapest point outside it. Kruskal processes links from cheapest to most expensive and keeps a link only if it joins two separate groups. You do not need a formal proof in the interview, but one sentence naming the cut property shows you know why greedy is allowed here when it is not allowed in, say, Coin Change.

Baseline: Kruskal on every edge

Build all n(n - 1) / 2 links with their costs, sort them, and walk the sorted list with a union-find structure. Take a link when its two points are in different groups and merge the groups; stop after n - 1 links. The sort dominates at O(n² log n) time, and storing every edge costs O(n²) memory. It is a fine opening and a reliable cross-check.

def cable_kruskal(spots):
    n = len(spots)
    links = []
    for i in range(n):
        for j in range(i + 1, n):
            gap = abs(spots[i][0] - spots[j][0]) + abs(spots[i][1] - spots[j][1])
            links.append((gap, i, j))
    links.sort()

    root = list(range(n))

    def find(a):
        while root[a] != a:
            root[a] = root[root[a]]  # path halving
            a = root[a]
        return a

    total, joined = 0, 0
    for gap, i, j in links:
        ri, rj = find(i), find(j)
        if ri != rj:
            root[ri] = rj
            total += gap
            joined += 1
            if joined == n - 1:
                break
    return total
Kruskal with union-find over all pairs, O(n² log n) time, O(n²) space.

Optimal for dense graphs: Prim with a distance array

Keep, for every point not yet in the tree, the cheapest link from it to any point already in the tree. Start with point 0 in the tree. Repeatedly pick the outside point with the smallest such cost, add that cost to the total, mark the point as inside, and use it to lower the costs of the remaining outside points. Each round scans an array of n entries twice, and there are n rounds, so the total is O(n²) time with O(n) memory. Because edge costs are computed on the fly, the edge list is never built.

Prim trace for (0,0) (3,1) (1,4) (6,6) (5,0)
RoundPoint addedCost paidCheapest links left for the outside points
1(0,0)0(3,1) 4, (1,4) 5, (6,6) 12, (5,0) 5
2(3,1)4(1,4) 5, (6,6) 8, (5,0) 3
3(5,0)3(1,4) 5, (6,6) 7
4(1,4)5(6,6) 7
5(6,6)7none; total 19
Prim trace for (0,0) (3,1) (1,4) (6,6) (5,0). Scroll sideways on a small screen.
def cable_prim(spots):
    n = len(spots)
    if n < 2:
        return 0
    inside = [False] * n
    cheapest = [float("inf")] * n
    cheapest[0] = 0
    total = 0
    for _ in range(n):
        pick = -1
        for v in range(n):
            if not inside[v] and (pick == -1 or cheapest[v] < cheapest[pick]):
                pick = v
        inside[pick] = True
        total += cheapest[pick]
        px, py = spots[pick]
        for v in range(n):
            if not inside[v]:
                gap = abs(px - spots[v][0]) + abs(py - spots[v][1])
                if gap < cheapest[v]:
                    cheapest[v] = gap
    return total
Python: Prim with an array, O(n²) time, O(n) space.
function cablePrim(spots) {
  const n = spots.length;
  if (n < 2) return 0;
  const inside = new Uint8Array(n);
  const cheapest = new Float64Array(n).fill(Infinity);
  cheapest[0] = 0;
  let total = 0;
  for (let round = 0; round < n; round++) {
    let pick = -1;
    for (let v = 0; v < n; v++) {
      if (!inside[v] && (pick === -1 || cheapest[v] < cheapest[pick])) pick = v;
    }
    inside[pick] = 1;
    total += cheapest[pick];
    const [px, py] = spots[pick];
    for (let v = 0; v < n; v++) {
      if (inside[v]) continue;
      const gap = Math.abs(px - spots[v][0]) + Math.abs(py - spots[v][1]);
      if (gap < cheapest[v]) cheapest[v] = gap;
    }
  }
  return total;
}
JavaScript: the same Prim loop with typed arrays.

A version of Prim with a binary heap is also common. On a sparse graph it wins, but on a complete graph it pushes up to n² entries and lands at O(n² log n), slower than the plain array. If you reach for the heap, say why the array is the better fit here and let the interviewer choose.

Time and space

Cost for n points (about n² / 2 possible links)
VersionTimeExtra space
Every spanning treeGrows faster than exponentiallyNot practical
Kruskal on all linksO(n² log n)O(n²) for the link list
Prim with a binary heapO(n² log n)O(n²) heap entries in the worst case
Prim with a plain arrayO(n²)O(n)
Cost for n points (about n² / 2 possible links). Scroll sideways on a small screen.

Edge cases

  • One point, or none: cost 0.
  • Two points: their distance.
  • Duplicate points: a link of cost 0, which both algorithms handle without special code.
  • All points on one line: the answer is the distance between the two extreme points.
  • Negative coordinates: absolute differences still work.

Mistakes to avoid

  • Using straight-line (Euclidean) distance instead of the horizontal plus vertical gap.
  • Connecting each point to its nearest neighbor and summing, which can leave separate clusters and double-count links.
  • Building the full edge list for Prim and then using a heap, which gives up the advantage of the dense-graph version.
  • Forgetting to skip points already in the tree when updating costs.
  • Union-find without path compression or union by size, which can degrade on long chains.

How to explain it out loud

Fictional example

Naming the structure, then picking the tool
Candidate
Every point must be reachable and I pay per link, so the cheapest answer has no cycles. That is a minimum spanning tree over all the points.
Candidate
Any two points can be linked, so the graph is complete. Kruskal would sort about n squared over two links. Prim with an array avoids building them at all.
Candidate
I keep the cheapest link from each outside point into the tree, add the smallest, and update the rest. That is n rounds of linear scans, so n squared time and linear space.

Number of Islands is the gentler graph warm-up, about finding connected groups rather than connecting them cheaply. House Robber and Coin Change show where greedy breaks and dynamic programming takes over, the opposite of this page. Longest Palindromic Substring is another problem where the usual interview answer is quadratic.

Where Natively fits

Graph problems often hide their structure behind a story, and spotting it is the skill to train. In practice on Mac or Windows, Natively can read a problem like this from a screenshot, point out that it reduces to a spanning tree, and give Prim or Kruskal code to compare with yours. Its transcript of the session shows whether you named the structure before you started coding. See the AI interview assistant page.

Questions people ask

What algorithm solves Min Cost to Connect All Points?

A minimum spanning tree algorithm. Treat each point as a node and the Manhattan distance between two points as the cost of linking them, then use Prim's or Kruskal's algorithm to find the cheapest set of links that connects everything.

Is Prim or Kruskal better for Min Cost to Connect All Points?

Prim with a simple distance array, because every pair of points can be linked and the graph is complete. It runs in O(n²) time and O(n) space, while Kruskal must build and sort about n² / 2 edges, costing O(n² log n) time and O(n²) memory.

What is the time complexity of Min Cost to Connect All Points?

O(n²) time and O(n) space with array-based Prim, which computes distances on the fly. Kruskal or heap-based Prim over all pairs take O(n² log n). Manhattan distance also allows faster specialized methods, but they are rarely expected in an interview.

Why is a greedy approach correct for minimum spanning trees?

Because of the cut property: for any split of the points into two groups, the cheapest link between the groups belongs to some minimum spanning tree. Prim and Kruskal only ever add such links.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP