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.
- 1 <= points.length <= 1000
- -10⁶ <= xi, yi <= 10⁶
- All pairs (xi, yi) are distinct.
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.
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.
Approach
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.
Two ways to solve it
Grow one tree and keep each outside point's cheapest link in an array.
- No edge list: links are priced on the fly.
- No heap: a scan picks the next point.
- Fits the input: every pair is a link, so O(n²) is the best possible order anyway.
List all n(n - 1) / 2 links, sort them, and keep each one that joins two separate groups.
- Simple logic: sort, then union-find.
- Cost: about 500,000 links to store and sort at n = 1,000.
The obvious first idea, and fast enough to pass.
Both build the same minimum spanning tree. The array version wins on this problem because the graph is complete: storing and sorting every link costs more than scanning n points n times. The steps, code and live demo follow the array version; Kruskal's code comes after the demo.
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.
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²).
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.
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.
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.
Code in Python, C++ and Java
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.
Common pitfalls
Linking each point to its nearest neighbour
for each point p:
link p to its closest other pointgrow 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
cost, u = heappop(heap) visited.add(u) total += cost
cost, u = heappop(heap)
if u in visited:
continue
visited.add(u)
total += costA 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
d = math.dist(points[u], points[v])
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.
Edge cases
The loop runs once, adds dist[0] = 0, and returns 0. Nothing needs linking.
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⁹.
Complexity
dist and the joined flags are stored; the 500,000 possible links are computed when needed and never kept.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.