Home
DSA Patterns
Heap / Priority Queue
Min Cost to Connect All Points
Min Cost to Connect All Points (LeetCode 1584)
Min Cost to Connect All Points (LeetCode 1584): connect every point at the least total Manhattan distance with Prim's algorithm: a min-heap always attaches the cheapest new point to the tree.
Problem Understanding
Min Cost to Connect All Points: given points[i] = [x, y], connecting two points costs their Manhattan distance |x1 - x2| + |y1 - y2|. Return the minimum total cost so that every point is connected, meaning there is exactly one path between any two points.
Example: points = [[0,0],[2,2],[3,10],[5,2],[7,0]] returns 20.
The Intuition: Grow One Tree, Cheapest Edge First
Connecting all points with no cycles and the least total cost is a minimum spanning tree. Prim's algorithm grows it one point at a time:
- Start with point 0 alone in the tree.
- Of all edges from a tree point to a non-tree point, take the cheapest. That edge is always safe: any spanning tree must cross from "in" to "out" somewhere, and the cheapest crossing can never make it worse.
- Repeat until every point is in.
A min-heap holds the candidate edges, so the cheapest is one pop away. Each new point pushes its distance to every outside point; entries for points that joined in the meantime are stale and skipped. It is the same pop-cheapest-then-push loop as Network Delay Time's Dijkstra, except the key is the edge cost alone, not the distance from a source.
Min Cost to Connect All Points Visualization
NUMBER ABOVE A POINT = ITS x,y · NUMBER ON AN EDGE = MANHATTAN COST
START AT POINT 0
in tree
0/5
cost
0
heap (cost, point)
Grow one tree from point 0. Heap = [(0, 0)]: point 0 joins for free
Next
Pop (0, 0): point 0 starts the tree
points
Points are drawn at their coordinates. The tree grows in green; the heap of candidate edges is listed beside it, cheapest first. Try Stale entry to see an old, more expensive entry popped and skipped.
Min Cost to Connect All Points Dry Run
Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
| Pop (cost, point) | Action | Total |
|---|---|---|
| (0, 0) | start the tree at point 0 | 0 |
| (4, 1) | add 0: 1 | 4 |
| (3, 3) | add 1: 3 | 7 |
| (4, 4) | add 3: 4 | 11 |
| three pops | points already in the tree: stale, skipped | 11 |
| (9, 2) | add 1: 2 | 20 |
Answer: 20, using 4 edges for 5 points.
Min Cost to Connect All Points LeetCode Solution
Lazy Prim with a heap. JavaScript and TypeScript include a small binary heap. C uses the O(n²) array version of Prim, which keeps the cheapest known cost for each outside point instead of a heap.
Min Cost to Connect All Points Code
1var minCostConnectPoints = function(points) {2 const n = points.length, inTree = Array(n).fill(false);3 const heap = [[0, 0]];4 let total = 0, added = 0;5 while (added < n) {6 const [cost, u] = pop(heap);7 if (inTree[u]) continue;8 inTree[u] = true;9 total += cost;10 added++;11 for (let v = 0; v < n; v++) {12 if (!inTree[v]) {13 const d = Math.abs(points[u][0] - points[v][0]) + Math.abs(points[u][1] - points[v][1]);14 push(heap, [d, v]);15 }16 }17 }18 return total;19};2021// Minimal binary min-heap on [cost, point] pairs.22function push(heap, item) {23 heap.push(item);24 let i = heap.length - 1;25 while (i > 0) {26 const p = (i - 1) >> 1;27 if (heap[p][0] <= heap[i][0]) break;28 [heap[p], heap[i]] = [heap[i], heap[p]];29 i = p;30 }31}3233function pop(heap) {34 const top = heap[0], last = heap.pop();35 if (heap.length) {36 heap[0] = last;37 let i = 0;38 while (true) {39 let m = i;40 const l = 2 * i + 1, r = l + 1;41 if (l < heap.length && heap[l][0] < heap[m][0]) m = l;42 if (r < heap.length && heap[r][0] < heap[m][0]) m = r;43 if (m === i) break;44 [heap[m], heap[i]] = [heap[i], heap[m]];45 i = m;46 }47 }48 return top;49}
Min Cost to Connect All Points in Python, Java, C++, TypeScript and C
Min Cost to Connect All Points in Python
class Solution:
def minCostConnectPoints(self, points: List[List[int]]) -> int:
n = len(points)
in_tree = [False] * n
heap = [(0, 0)]
total = added = 0
while added < n:
cost, u = heapq.heappop(heap)
if in_tree[u]:
continue
in_tree[u] = True
total += cost
added += 1
for v in range(n):
if not in_tree[v]:
d = abs(points[u][0] - points[v][0]) + abs(points[u][1] - points[v][1])
heapq.heappush(heap, (d, v))
return totalMin Cost to Connect All Points in Java
class Solution {
public int minCostConnectPoints(int[][] points) {
int n = points.length, total = 0, added = 0;
boolean[] inTree = new boolean[n];
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> a[0] - b[0]);
heap.offer(new int[]{0, 0});
while (added < n) {
int[] top = heap.poll();
int cost = top[0], u = top[1];
if (inTree[u]) continue;
inTree[u] = true;
total += cost;
added++;
for (int v = 0; v < n; v++) {
if (!inTree[v]) {
int d = Math.abs(points[u][0] - points[v][0]) + Math.abs(points[u][1] - points[v][1]);
heap.offer(new int[]{d, v});
}
}
}
return total;
}
}Min Cost to Connect All Points in C++
class Solution {
public:
int minCostConnectPoints(vector<vector<int>>& points) {
int n = points.size(), total = 0, added = 0;
vector<bool> inTree(n, false);
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> heap;
heap.push({0, 0});
while (added < n) {
auto [cost, u] = heap.top();
heap.pop();
if (inTree[u]) continue;
inTree[u] = true;
total += cost;
added++;
for (int v = 0; v < n; v++) {
if (!inTree[v]) {
int d = abs(points[u][0] - points[v][0]) + abs(points[u][1] - points[v][1]);
heap.push({d, v});
}
}
}
return total;
}
};Min Cost to Connect All Points in TypeScript
function minCostConnectPoints(points: number[][]): number {
const n = points.length, inTree: boolean[] = Array(n).fill(false);
const heap: number[][] = [[0, 0]];
let total = 0, added = 0;
while (added < n) {
const [cost, u] = pop(heap);
if (inTree[u]) continue;
inTree[u] = true;
total += cost;
added++;
for (let v = 0; v < n; v++) {
if (!inTree[v]) {
const d = Math.abs(points[u][0] - points[v][0]) + Math.abs(points[u][1] - points[v][1]);
push(heap, [d, v]);
}
}
}
return total;
}
// Minimal binary min-heap on [cost, point] pairs.
function push(heap: number[][], item: number[]): void {
heap.push(item);
let i = heap.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (heap[p][0] <= heap[i][0]) break;
[heap[p], heap[i]] = [heap[i], heap[p]];
i = p;
}
}
function pop(heap: number[][]): number[] {
const top = heap[0], last = heap.pop()!;
if (heap.length) {
heap[0] = last;
let i = 0;
while (true) {
let m = i;
const l = 2 * i + 1, r = l + 1;
if (l < heap.length && heap[l][0] < heap[m][0]) m = l;
if (r < heap.length && heap[r][0] < heap[m][0]) m = r;
if (m === i) break;
[heap[m], heap[i]] = [heap[i], heap[m]];
i = m;
}
}
return top;
}Min Cost to Connect All Points in C
int minCostConnectPoints(int** points, int pointsSize, int* pointsColSize) {
int n = pointsSize, total = 0;
int* best = malloc(n * sizeof(int));
bool* inTree = calloc(n, sizeof(bool));
for (int i = 0; i < n; i++) best[i] = INT_MAX;
best[0] = 0;
for (int round = 0; round < n; round++) {
int u = -1;
for (int i = 0; i < n; i++)
if (!inTree[i] && (u == -1 || best[i] < best[u])) u = i;
inTree[u] = true;
total += best[u];
for (int v = 0; v < n; v++) {
if (!inTree[v]) {
int d = abs(points[u][0] - points[v][0]) + abs(points[u][1] - points[v][1]);
if (d < best[v]) best[v] = d;
}
}
}
free(best);
free(inTree);
return total;
}Edge Cases & Common Mistakes
- One point: nothing to connect; the answer is 0.
- Forgetting the in-tree check: a stale entry would add the same point twice and overcount the cost.
- Euclidean instead of Manhattan: the cost is
|dx| + |dy|, no square root. - Building all n² edges for Kruskal: works, but sorts about n²/2 edges; Prim avoids the full list.
- Ties: any cheapest edge is fine; different tie choices give different trees with the same total.
Summary
Treat the points as a complete graph with Manhattan weights and build a minimum spanning tree with Prim's algorithm: pop the cheapest attachment, skip it if stale, add the point and push its costs to every outside point. O(n² log n) time with a heap, or O(n²) with the array version.
More practice: DSA interview questions with answers · patterns cheat sheet
