Min Cost to Connect All Points (LeetCode 1584): Solution and Explanation
You are given points on a 2D grid, and connecting two points costs their Manhattan distance. Find the minimum total cost to connect every point so that any point can reach any other through the chosen connections.
Watch it run step by step
Try your own input and write the code →Intuition
Connecting everything as cheaply as possible, with no requirement on path lengths, is the definition of a minimum spanning tree. Any extra edge beyond a tree would create a cycle, and removing the most expensive edge of that cycle would keep things connected for less. So the answer is the total weight of the MST of the complete graph where every pair of points is joined by an edge with weight equal to their Manhattan distance.
Brute force over subsets of edges is out of the question, so you reach for a standard MST algorithm. Kruskal's sorts all edges and adds them with union-find. Prim's grows a single tree from a starting point, repeatedly adding the cheapest edge that leads to a point not yet in the tree. The reference solution uses Prim's with a min-heap.
The heap holds candidate edges as [cost, point]. When you pop a point that is already in the tree, that edge is stale because the point was reached more cheaply earlier, so you skip it. When you pop a new point, its cost is exactly the cheapest connection from the current tree, which is the cut property that guarantees Prim's is correct. Then you push edges from the new point to every point still outside the tree.
Approach: Prim's algorithm with a lazy min-heap
- Build an adjacency list where each pair of points
iandjgets an edge of weightabs(x1 - x2) + abs(y1 - y2)in both directions. - Start the heap with
[0, 0], meaning point 0 can join the tree for free, and keep avisitset. - While fewer than N points are in the tree, pop the cheapest
[cost, i]. - If
iis already visited, skip the stale entry. - Otherwise add
costto the result and markias visited. - Push
[neiCost, nei]for every neighbor not yet visited, and return the result when all points are in.
Step-by-step example
points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
- Point 0 joins at cost 0 and pushes edges to points 1, 2, 3 and 4 with costs 4, 13, 7 and 7.
- The cheapest is point 1 at cost 4, so the total is 4. From (2,2) it pushes point 2 at 9, point 3 at 3 and point 4 at 7.
- Point 3 joins at cost 3, total 7. From (5,2) it pushes point 2 at 10 and point 4 at 4.
- Point 4 joins at cost 4, total 11, and pushes point 2 at 14.
- The heap now pops stale entries for points 3 and 4 and skips them, then pops point 2 at cost 9. The total is 20, and all five points are connected.
Code: Python, Java, C++
1class Solution:
2 def minCostConnectPoints(self, points: List[List[int]]) -> int:
3 N = len(points)
4 adj = {i:[] for i in range(N)}
5 for i in range(N):
6 x1, y1 = points[i]
7 for j in range(i + 1, N):
8 x2, y2 = points[j]
9 dist = abs(x1 - x2) + abs(y1 - y2)
10 adj[i].append([dist, j])
11 adj[j].append([dist, i])
12
13 res = 0
14 visit = set()
15 minH = [[0, 0]] # [cost, point]
16
17 while len(visit) < N:
18 cost, i = heapq.heappop(minH)
19 if i in visit:
20 continue
21 res += cost
22 visit.add(i)
23 for neiCost, nei in adj[i]:
24 if nei not in visit:
25 heapq.heappush(minH, [neiCost, nei])
26 return res1class Solution {
2 public int minCostConnectPoints(int[][] points) {
3 int N = points.length;
4 List<int[]>[] adj = new ArrayList[N];
5 for (int i = 0; i < N; i++) adj[i] = new ArrayList<>();
6
7 for (int i = 0; i < N; i++) {
8 for (int j = i + 1; j < N; j++) {
9 int dist = Math.abs(points[i][0] - points[j][0]) + Math.abs(points[i][1] - points[j][1]);
10 adj[i].add(new int[]{dist, j});
11 adj[j].add(new int[]{dist, i});
12 }
13 }
14
15 int res = 0;
16 Set<Integer> visit = new HashSet<>();
17 PriorityQueue<int[]> minH = new PriorityQueue<>((a, b) -> a[0] - b[0]);
18 minH.add(new int[]{0, 0});
19
20 while (visit.size() < N) {
21 int[] curr = minH.poll();
22 if (visit.contains(curr[1])) continue;
23 res += curr[0];
24 visit.add(curr[1]);
25 for (int[] nei : adj[curr[1]]) {
26 if (!visit.contains(nei[1])) {
27 minH.add(nei);
28 }
29 }
30 }
31 return res;
32 }
33}1class Solution {
2public:
3 int minCostConnectPoints(vector<vector<int>>& points) {
4 int N = points.size();
5 vector<vector<pair<int, int>>> adj(N);
6
7 for (int i = 0; i < N; i++) {
8 for (int j = i + 1; j < N; j++) {
9 int dist = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]);
10 adj[i].push_back({dist, j});
11 adj[j].push_back({dist, i});
12 }
13 }
14
15 int res = 0;
16 unordered_set<int> visit;
17 priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> minH;
18 minH.push({0, 0});
19
20 while (visit.size() < N) {
21 auto [cost, i] = minH.top();
22 minH.pop();
23 if (visit.count(i)) continue;
24 res += cost;
25 visit.insert(i);
26 for (auto& [neiCost, nei] : adj[i]) {
27 if (!visit.count(nei)) {
28 minH.push({neiCost, nei});
29 }
30 }
31 }
32 return res;
33 }
34};Time and space complexity
O(n² log n)
The complete graph has about n² / 2 edges, every one of them can be pushed onto the heap, and each push or pop costs O(log n²), which is O(log n).
O(n²)
The adjacency list stores every pair of points, and the heap can hold O(n²) entries in the worst case.
Other approaches
Prim's with a distance array (time O(n²), space O(n))
Skip the heap and adjacency list. Keep dist[j], the cheapest known connection for every point outside the tree, pick the minimum by linear scan and relax distances from the new point. On a dense graph this is optimal and uses linear memory.
Kruskal's with union-find (time O(n² log n), space O(n²))
Generate all edges, sort them by cost and add each one that connects two different components until n - 1 edges are used. Easy to reason about, but sorting n² edges is the bottleneck.
Common mistakes
- Forgetting to skip points that are already visited when popping double counts costs from stale heap entries.
- Starting the inner loop at
j = 0instead ofi + 1adds zero-cost self loops and stores every edge four times, doubling memory on inputs of 1,000 points. - Using Euclidean distance instead of Manhattan distance gives the wrong costs.
- Adding each point's popped cost before checking whether it is visited inflates the result.
Frequently asked questions
Why is this a minimum spanning tree problem?
You need every point connected at minimum total cost, with no constraint on individual path lengths. A cheapest connected subgraph never contains a cycle, so it is a spanning tree, and the cheapest one is the MST.
Prim's or Kruskal's for min cost to connect all points?
Both are accepted. The graph is complete and dense, so Prim's is a natural fit, and the array-based version of Prim's runs in O(n²) without sorting all edges.
Why do we skip visited points when popping?
The lazy heap can contain several entries for the same point with different costs. Only the first, cheapest one is valid; later ones are stale and must be ignored.
What is the time complexity?
The heap version shown is O(n² log n) time and O(n²) space because it considers every pair of points. The array version of Prim's improves this to O(n²) time and O(n) space.