LeetCode #1584 Medium

Min Cost to Connect All Points

Min Cost to Connect All Points is LeetCode 1584 (Medium). You get n distinct points on a 2D plane. Linking two points costs their Manhattan distance, |xi - xj| + |yi - yj|. Return the smallest total cost that connects every point, so that a path of links joins any two points.

  • Any point may be linked to any other, so every pair is a possible link: n(n - 1) / 2 of them.
  • With up to 1,000 points that is about 500,000 links, and that number decides which algorithm to use.
Constraints
  • 1 <= points.length <= 1000
  • -10⁶ <= xi, yi <= 10⁶
  • All pairs (xi, yi) are distinct.
graphminimum-spanning-treeprim
Open on LeetCode ↗
02

Intuition

The cheapest network has no loop: dropping one link of a loop keeps everything connected for less. So the answer is a minimum spanning tree of the graph in which every pair of points is linked, priced by Manhattan distance.

Grow the tree from point 0, keeping dist[v] for every outside point: the cost of its cheapest link to any point already inside. Each round, the outside point with the smallest dist joins and its cost is added.

  • Why that link is safe: the outside points must reach the tree through some link that crosses into it, and none is cheaper.
  • Why one sweep updates everything: only the links from the newcomer are new.
How to spot this pattern

Connecting every point as cheaply as possible, when any pair may be linked, is a minimum spanning tree problem. When the links are implied by coordinates instead of listed, the graph is complete, and that favours an O(n²) method that never builds the edge list.

03

Approach

Try it first

Before reading on, decide what you need to remember about each point that is not connected yet, so that choosing the next point is a simple scan. Then check that one round costs O(n). Aim for O(n²) time and O(n) extra space.

1

Start the tree at point 0

Set dist[0] = 0 and every other dist to infinity. Point 0 joins first at no cost. Any start works, because the finished tree contains every point whichever one it grew from.

2

Pick the closest outside point

Scan every point not yet in the tree and take the one with the smallest dist. The scan costs O(n), and there are exactly n rounds, so all the scans together cost O(n²).

3

Add it and pay for its link

Mark the point as joined and add dist[u] to the total. For point 0 that adds 0; for every later point it is the price of the one link that connects it to the tree.

4

Update the outside points from the newcomer

For each point v still outside, compute the Manhattan distance from u to v and lower dist[v] if it is smaller. Doing this as each point joins keeps every dist up to date for the next scan.

5

Stop after n rounds

Each round adds exactly one new point, because the scan only looks at points outside the tree. After n rounds every point is connected and the total is the answer; there is no edge count or cycle check to do.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def minCostConnectPoints(self, points):
▶3 n = len(points)
▶4 dist = [float("inf")] * n
▶5 dist[0] = 0
▶6 in_tree = [False] * n
▶7 total = 0
▶8 for _ in range(n):
▶9 u = -1
▶10 for v in range(n):
▶11 if not in_tree[v] and (u == -1 or dist[v] < dist[u]):
▶12 u = v
▶13 in_tree[u] = True
▶14 total += dist[u]
▶15 x, y = points[u]
▶16 for v in range(n):
▶17 if not in_tree[v]:
▶18 d = abs(x - points[v][0]) + abs(y - points[v][1])
▶19 if d < dist[v]:
▶20 dist[v] = d
▶21 return total
link in the treelink being priced01234cheapest link into the treepoint 0(0, 0)0point 1(2, 2)∞point 2(3, 10)∞point 3(5, 2)∞point 4(7, 0)∞price of the linkno link being pricedtotal0point 0 starts at cost 0, the rest at ∞
dist[0, ∞, ∞, ∞, ∞]cheapest link into the tree
total0
Each tile under the plot is one point's cheapest known link into the tree. Nothing is in the tree yet, so every point is at ∞, except point 0: it will join first, and the first point needs no link, so it costs 0.
link in the treelink being priced01234cheapest link into the treepoint 0(0, 0)0point 1(2, 2)∞point 2(3, 10)∞point 3(5, 2)∞point 4(7, 0)∞price of the linkno link being pricedtotal0point 0 is cheapest (0) → it joins
u0smallest cost outside
total0+ 0
Point 0 has the smallest cost, 0, so it joins first and the total stays 0. Now only links from point 0 are new, so each outside point is priced against it.
link in the treelink being priced01234cheapest link into the treepoint 0(0, 0)0point 1(2, 2)4point 2(3, 10)∞point 3(5, 2)∞point 4(7, 0)∞price of the link2+2=4<∞acrossup/downcostbesttotal0point 1: 4 beats ∞ → new best
cost 0→14across + up/down
dist[1]4
From point 0 to point 1 is 2 across and 2 up or down, so the link costs 4. Point 1 had no link into the tree yet, so this becomes its best.
link in the treelink being priced01234cheapest link into the treepoint 0(0, 0)0point 1(2, 2)4point 2(3, 10)13point 3(5, 2)∞point 4(7, 0)∞price of the link3+10=13<∞acrossup/downcostbesttotal0point 2: 13 beats ∞ → new best
cost 0→213across + up/down
dist[2]13
From point 0 to point 2 is 3 across and 10 up or down, so the link costs 13. Point 2 had no link into the tree yet, so this becomes its best.
link in the treelink being priced01234cheapest link into the treepoint 0(0, 0)0point 1(2, 2)4point 2(3, 10)13point 3(5, 2)7point 4(7, 0)∞price of the link5+2=7<∞acrossup/downcostbesttotal0point 3: 7 beats ∞ → new best
cost 0→37across + up/down
dist[3]7
From point 0 to point 3 is 5 across and 2 up or down, so the link costs 7. Point 3 had no link into the tree yet, so this becomes its best.
link in the treelink being priced01234cheapest link into the treepoint 0(0, 0)0point 1(2, 2)4point 2(3, 10)13point 3(5, 2)7point 4(7, 0)7price of the link7+0=7<∞acrossup/downcostbesttotal0point 4: 7 beats ∞ → new best
cost 0→47across + up/down
dist[4]7
From point 0 to point 4 is 7 across and 0 up or down, so the link costs 7. Point 4 had no link into the tree yet, so this becomes its best.
link in the treelink being priced01234cheapest link into the treepoint 0(0, 0)0point 1(2, 2)4point 2(3, 10)13point 3(5, 2)7point 4(7, 0)7price of the linkno link being pricedtotal4point 1 is cheapest (4) → it joins
u1smallest cost outside
total4+ 4
Among the points outside the tree, point 1 has the smallest cost, 4, through its link to point 0. Every other way into the tree from outside costs at least 4, so this link is safe to keep. The total becomes 4. Now only links from point 1 are new, so each outside point is priced against it.
link in the treelink being priced01234cheapest link into the treepoint 0(0, 0)0point 1(2, 2)4point 2(3, 10)9point 3(5, 2)7point 4(7, 0)7price of the link1+8=9<13acrossup/downcostbesttotal4point 2: 9 beats 13 → new best
cost 1→29across + up/down
dist[2]9
From point 1 to point 2 is 1 across and 8 up or down, so the link costs 9. That is cheaper than its old best of 13, so point 2 now links through 1.
link in the treelink being priced01234cheapest link into the treepoint 0(0, 0)0point 1(2, 2)4point 2(3, 10)9point 3(5, 2)3point 4(7, 0)7price of the link3+0=3<7acrossup/downcostbesttotal4point 3: 3 beats 7 → new best
cost 1→33across + up/down
dist[3]3
From point 1 to point 3 is 3 across and 0 up or down, so the link costs 3. That is cheaper than its old best of 7, so point 3 now links through 1.
link in the treelink being priced01234cheapest link into the treepoint 0(0, 0)0point 1(2, 2)4point 2(3, 10)9point 3(5, 2)3point 4(7, 0)7price of the link5+2=7≥7acrossup/downcostbesttotal4point 4: 7 is not cheaper than 7 → keep
cost 1→47across + up/down
dist[4]7
From point 1 to point 4 is 5 across and 2 up or down, so the link costs 7. Its current best, 7, is just as cheap, so it keeps that link.
link in the treelink being priced01234cheapest link into the treepoint 0(0, 0)0point 1(2, 2)4point 2(3, 10)9point 3(5, 2)3point 4(7, 0)7price of the linkno link being pricedtotal7point 3 is cheapest (3) → it joins
u3smallest cost outside
total7+ 3
Among the points outside the tree, point 3 has the smallest cost, 3, through its link to point 1. Every other way into the tree from outside costs at least 3, so this link is safe to keep. The total becomes 7. Now only links from point 3 are new, so each outside point is priced against it.
link in the treelink being priced01234cheapest link into the treepoint 0(0, 0)0point 1(2, 2)4point 2(3, 10)9point 3(5, 2)3point 4(7, 0)7price of the link2+8=10≥9acrossup/downcostbesttotal7point 2: 10 is not cheaper than 9 → keep
cost 3→210across + up/down
dist[2]9
From point 3 to point 2 is 2 across and 8 up or down, so the link costs 10. Its current best, 9, is cheaper, so it keeps that link.
link in the treelink being priced01234cheapest link into the treepoint 0(0, 0)0point 1(2, 2)4point 2(3, 10)9point 3(5, 2)3point 4(7, 0)4price of the link2+2=4<7acrossup/downcostbesttotal7point 4: 4 beats 7 → new best
cost 3→44across + up/down
dist[4]4
From point 3 to point 4 is 2 across and 2 up or down, so the link costs 4. That is cheaper than its old best of 7, so point 4 now links through 3.
link in the treelink being priced01234cheapest link into the treepoint 0(0, 0)0point 1(2, 2)4point 2(3, 10)9point 3(5, 2)3point 4(7, 0)4price of the linkno link being pricedtotal11point 4 is cheapest (4) → it joins
u4smallest cost outside
total11+ 4
Among the points outside the tree, point 4 has the smallest cost, 4, through its link to point 3. Every other way into the tree from outside costs at least 4, so this link is safe to keep. The total becomes 11. Now only links from point 4 are new, so each outside point is priced against it.
link in the treelink being priced01234cheapest link into the treepoint 0(0, 0)0point 1(2, 2)4point 2(3, 10)9point 3(5, 2)3point 4(7, 0)4price of the link4+10=14≥9acrossup/downcostbesttotal11point 2: 14 is not cheaper than 9 → keep
cost 4→214across + up/down
dist[2]9
From point 4 to point 2 is 4 across and 10 up or down, so the link costs 14. Its current best, 9, is cheaper, so it keeps that link.
link in the treelink being priced01234cheapest link into the treepoint 0(0, 0)0point 1(2, 2)4point 2(3, 10)9point 3(5, 2)3point 4(7, 0)4price of the linkno link being pricedtotal20point 2 is cheapest (9) → it joins
u2smallest cost outside
total20+ 9
Among the points outside the tree, point 2 has the smallest cost, 9, through its link to point 1. Every other way into the tree from outside costs at least 9, so this link is safe to keep. The total becomes 20. That was the last point.
link in the treelink being priced01234cheapest link into the treepoint 0(0, 0)0point 1(2, 2)4point 2(3, 10)9point 3(5, 2)3point 4(7, 0)4price of the linkevery point joinedtotal20all 5 points joined → total 20
result20
Every point is in the tree after 5 rounds, joined by 4 green links. Their costs add up to 20, the minimum. The array never held more than one number per point, and no list of all links was built.
05

Kruskal's with union-find

Build every link with its Manhattan cost and sort them from cheapest. Walk the sorted list with a union-find: a link whose two points are already in the same group would close a loop, so it is skipped; any other link is kept and merges the two groups. Stop once n - 1 links are kept.

▶1class Solution:
▶2 def minCostConnectPoints(self, points):
▶3 n = len(points)
▶4 edges = []
▶5 for i in range(n):
▶6 for j in range(i + 1, n):
▶7 d = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1])
▶8 edges.append((d, i, j))
▶9 edges.sort()
▶10 
▶11 parent = list(range(n))
▶12 
▶13 def find(x):
▶14 while parent[x] != x:
▶15 parent[x] = parent[parent[x]]
▶16 x = parent[x]
▶17 return x
▶18 
▶19 total = used = 0
▶20 for d, i, j in edges:
▶21 a, b = find(i), find(j)
▶22 if a == b:
▶23 continue
▶24 parent[a] = b
▶25 total += d
▶26 used += 1
▶27 if used == n - 1:
▶28 break
▶29 return total
06

Common pitfalls

Linking each point to its nearest neighbour

✗ Wrong
for each point p:
    link p to its closest other point
✓ Right
grow one tree: always add the cheapest link
from the tree to a point outside it

Nearest neighbours can pair up into separate groups. For [[0,0],[2,2],[11,1],[13,3]] the links are 0–1 and 2–3, a total of 8, but the two pairs are never joined. The correct answer is 18, because one link of cost 10 must bridge the gap.

Counting a point twice in heap-based Prim's

✗ Wrong
cost, u = heappop(heap)
visited.add(u)
total += cost
✓ Right
cost, u = heappop(heap)
if u in visited:
    continue
visited.add(u)
total += cost

A heap holds one entry per link that was pushed, so the same point can come out several times with older, higher costs. Without the skip, the problem's first example, [[0,0],[2,2],[3,10],[5,2],[7,0]], returns 41 instead of 20. The array version has no such entries: dist[v] is one number per point.

Using straight-line distance

✗ Wrong
d = math.dist(points[u], points[v])
✓ Right
d = abs(x - points[v][0]) + abs(y - points[v][1])

The problem prices a link by Manhattan distance. For [[0,0],[3,4]] the straight-line distance is 5, but the expected answer is 7.

07

Edge cases

A single point

The loop runs once, adds dist[0] = 0, and returns 0. Nothing needs linking.

Can the total overflow a 32-bit int?

No. Visiting the points from left to right is one way to connect them, and it costs at most 2 × 10⁶ across plus 999 × 2 × 10⁶ up and down, about 2.0 × 10⁹. The minimum is no larger, so it stays under the int limit of about 2.147 × 10⁹.

08

Complexity

Time
O(n²)
Space
O(n)
n rounds, each with one O(n) scan to pick a point and one O(n) sweep to update the others. Only dist and the joined flags are stored; the 500,000 possible links are computed when needed and never kept.
09

Min Cost to Connect All Points FAQ

Why not use a heap here?

A heap helps when each point has only a few links. Here each point links to all the others, so heap-based Prim's pushes up to n² entries: O(n² log n) time and O(n²) memory. The array version does the same rounds with a plain scan, in O(n²) time and O(n) memory.

Can different trees give the same minimum cost?

Yes. When two links tie, either can be chosen and the tree shape changes, but the total cost is always the same. LeetCode only checks the total, so the order in which tied points join does not matter.