Min Cost to Connect All Points
Min Cost to Connect All Points is a medium graphs problem solved with the minimum spanning tree pattern.
The best approach, optimal (prim with an array of best distances), runs in O(n^2) time and O(n) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (grow the tree, scanning every pair) up.
Problem
You are given an array points, where points[i] = [x_i, y_i] is a point on a 2D grid.
Linking two points [x_i, y_i] and [x_j, y_j] costs their Manhattan distance: |x_i - x_j| + |y_i - y_j|.
Return the minimum total cost of links needed so that every point is connected to every other point. Two points are connected when there is a path of links between them, so a point does not need a direct link to every other point.
Examples
Example 1
- Input
points = [[1,1],[4,2],[6,6],[0,5],[8,1]]- Output
20- Why
- Link [1,1]-[4,2] (cost 4), [1,1]-[0,5] (cost 5), [4,2]-[8,1] (cost 5) and [4,2]-[6,6] (cost 6). That joins all five points for 4 + 5 + 5 + 6 = 20, and no cheaper set of links does.
Example 2
- Input
points = [[3,-4]]- Output
0- Why
- A single point is already connected, so no link is needed.
Example 3
- Input
points = [[-2,1],[3,1],[0,-3]]- Output
11- Why
- The three possible links cost 5, 6 and 7. Two of them are enough to join three points, so take the two cheapest: 5 + 6 = 11.
Constraints
1 <= points.length <= 1000-10^6 <= x_i, y_i <= 10^6- All points are distinct.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (grow the tree, scanning every pair) | O(n^3) | O(n) |
| Kruskal with union-find | O(n^2 log n) | O(n^2) |
| Optimal (Prim with an array of best distances) | O(n^2) | O(n) |
1Brute force (grow the tree, scanning every pair)
O(n^3)Each of the n - 1 steps looks at up to n times n pairs.O(n)Only the in-tree flags.Start a tree with point 0. At every step, look at every pair made of one point inside the tree and one point outside, and add the outside point whose link is cheapest. The cheapest link across the boundary of the tree is always safe to take, so after n - 1 additions the tree is a minimum spanning tree. This version recomputes every crossing link from scratch at each step.
- Mark point 0 as in the tree. cost = 0.
- Repeat n - 1 times: for every i in the tree and every j outside it, compute the Manhattan distance and remember the smallest one and its j.
- Put that j in the tree and add the smallest distance to cost.
- Return cost.
class Solution {
public int minCostConnectPoints(int[][] points) {
int n = points.length;
boolean[] inTree = new boolean[n];
inTree[0] = true;
int cost = 0;
for (int added = 1; added < n; added++) {
int best = Integer.MAX_VALUE, pick = -1;
for (int i = 0; i < n; i++) {
if (!inTree[i]) continue;
for (int j = 0; j < n; j++) {
if (inTree[j]) continue;
int d = Math.abs(points[i][0] - points[j][0]) + Math.abs(points[i][1] - points[j][1]);
if (d < best) { best = d; pick = j; }
}
}
inTree[pick] = true;
cost += best;
}
return cost;
}
}class Solution:
def minCostConnectPoints(self, points: List[List[int]]) -> int:
n = len(points)
in_tree = [False] * n
in_tree[0] = True
cost = 0
for _ in range(1, n):
best, pick = float('inf'), -1
for i in range(n):
if not in_tree[i]:
continue
for j in range(n):
if in_tree[j]:
continue
d = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1])
if d < best:
best, pick = d, j
in_tree[pick] = True
cost += best
return costclass Solution {
public:
int minCostConnectPoints(vector<vector<int>>& points) {
int n = points.size();
vector<bool> inTree(n, false);
inTree[0] = true;
int cost = 0;
for (int added = 1; added < n; added++) {
int best = INT_MAX, pick = -1;
for (int i = 0; i < n; i++) {
if (!inTree[i]) continue;
for (int j = 0; j < n; j++) {
if (inTree[j]) continue;
int d = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]);
if (d < best) { best = d; pick = j; }
}
}
inTree[pick] = true;
cost += best;
}
return cost;
}
};function minCostConnectPoints(points) {
const n = points.length;
const inTree = new Array(n).fill(false);
inTree[0] = true;
let cost = 0;
for (let added = 1; added < n; added++) {
let best = Infinity, pick = -1;
for (let i = 0; i < n; i++) {
if (!inTree[i]) continue;
for (let j = 0; j < n; j++) {
if (inTree[j]) continue;
const d = Math.abs(points[i][0] - points[j][0]) + Math.abs(points[i][1] - points[j][1]);
if (d < best) { best = d; pick = j; }
}
}
inTree[pick] = true;
cost += best;
}
return cost;
}2Kruskal with union-find
O(n^2 log n)There are about n^2 / 2 edges and sorting them costs O(n^2 log n). The union-find work is almost linear in the number of edges.O(n^2)The edge list holds n(n - 1) / 2 entries.List every pair of points as an edge with its Manhattan distance and sort the edges from cheapest to dearest. Walk through them and keep an edge only if its two points are still in different groups; otherwise it would close a loop and add nothing. A union-find structure answers "same group?" and merges two groups in nearly constant time. Stop once n - 1 edges are kept.
- Build all n(n - 1) / 2 edges [distance, i, j] and sort them by distance.
- Make a union-find where every point is its own group: parent[i] = i. find walks up to the group's root, halving the path as it goes.
- For each edge, find the roots of i and j. Same root: skip it. Different roots: link one root under the other, add the distance to cost and count the edge.
- When n - 1 edges are kept, every point is in one group; return cost.
class Solution {
private int[] parent;
private int find(int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
public int minCostConnectPoints(int[][] points) {
int n = points.length;
List<int[]> edges = new ArrayList<>();
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
edges.add(new int[] { Math.abs(points[i][0] - points[j][0]) + Math.abs(points[i][1] - points[j][1]), i, j });
edges.sort((a, b) -> Integer.compare(a[0], b[0]));
parent = new int[n];
for (int i = 0; i < n; i++) parent[i] = i;
int cost = 0, used = 0;
for (int[] e : edges) {
if (used == n - 1) break;
int ra = find(e[1]), rb = find(e[2]);
if (ra == rb) continue;
parent[ra] = rb;
cost += e[0];
used++;
}
return cost;
}
}class Solution:
def minCostConnectPoints(self, points: List[List[int]]) -> int:
n = len(points)
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
edges = []
for i in range(n):
for j in range(i + 1, n):
edges.append((abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]), i, j))
edges.sort()
cost = used = 0
for d, i, j in edges:
if used == n - 1:
break
ra, rb = find(i), find(j)
if ra == rb:
continue
parent[ra] = rb
cost += d
used += 1
return costclass Solution {
vector<int> parent;
int find(int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
public:
int minCostConnectPoints(vector<vector<int>>& points) {
int n = points.size();
vector<array<int, 3>> edges;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
edges.push_back({abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]), i, j});
sort(edges.begin(), edges.end());
parent.assign(n, 0);
for (int i = 0; i < n; i++) parent[i] = i;
int cost = 0, used = 0;
for (auto& e : edges) {
if (used == n - 1) break;
int ra = find(e[1]), rb = find(e[2]);
if (ra == rb) continue;
parent[ra] = rb;
cost += e[0];
used++;
}
return cost;
}
};function minCostConnectPoints(points) {
const n = points.length;
const parent = Array.from({ length: n }, (_, i) => i);
const find = (x) => {
while (parent[x] !== x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
};
const edges = [];
for (let i = 0; i < n; i++)
for (let j = i + 1; j < n; j++)
edges.push([Math.abs(points[i][0] - points[j][0]) + Math.abs(points[i][1] - points[j][1]), i, j]);
edges.sort((a, b) => a[0] - b[0]);
let cost = 0, used = 0;
for (const [d, i, j] of edges) {
if (used === n - 1) break;
const ra = find(i), rb = find(j);
if (ra === rb) continue;
parent[ra] = rb;
cost += d;
used++;
}
return cost;
}3Optimal (Prim with an array of best distances)
O(n^2)Each of the n rounds makes two scans over n points.O(n)The dist array and the in-tree flags.Grow one tree from point 0, as in the brute force, but remember for every outside point its cheapest link to the tree so far, in an array dist. Picking the next point is then one scan of dist, and after adding point u only u's links can improve anything, so one more scan updates dist. On a complete graph this O(n^2) is the best possible, since every pair may matter, and it needs no edge list.
- dist[i] = infinity for every point, dist[0] = 0, and no point is in the tree yet. cost = 0.
- Repeat n times: pick the outside point u with the smallest dist. Put it in the tree and add dist[u] to cost (0 for the first point).
- For every outside point v, compute the distance from u to v and lower dist[v] if it is smaller.
- Return cost.
class Solution {
public int minCostConnectPoints(int[][] points) {
int n = points.length;
int[] dist = new int[n];
Arrays.fill(dist, Integer.MAX_VALUE);
boolean[] inTree = new boolean[n];
dist[0] = 0;
int cost = 0;
for (int k = 0; k < n; k++) {
int u = -1;
for (int i = 0; i < n; i++)
if (!inTree[i] && (u == -1 || dist[i] < dist[u])) u = i;
inTree[u] = true;
cost += dist[u];
for (int v = 0; v < n; v++) {
if (inTree[v]) continue;
int d = Math.abs(points[u][0] - points[v][0]) + Math.abs(points[u][1] - points[v][1]);
if (d < dist[v]) dist[v] = d;
}
}
return cost;
}
}class Solution:
def minCostConnectPoints(self, points: List[List[int]]) -> int:
n = len(points)
dist = [float('inf')] * n
in_tree = [False] * n
dist[0] = 0
cost = 0
for _ in range(n):
u = -1
for i in range(n):
if not in_tree[i] and (u == -1 or dist[i] < dist[u]):
u = i
in_tree[u] = True
cost += dist[u]
ux, uy = points[u]
for v in range(n):
if in_tree[v]:
continue
d = abs(ux - points[v][0]) + abs(uy - points[v][1])
if d < dist[v]:
dist[v] = d
return costclass Solution {
public:
int minCostConnectPoints(vector<vector<int>>& points) {
int n = points.size();
vector<int> dist(n, INT_MAX);
vector<bool> inTree(n, false);
dist[0] = 0;
int cost = 0;
for (int k = 0; k < n; k++) {
int u = -1;
for (int i = 0; i < n; i++)
if (!inTree[i] && (u == -1 || dist[i] < dist[u])) u = i;
inTree[u] = true;
cost += dist[u];
for (int v = 0; v < n; v++) {
if (inTree[v]) continue;
int d = abs(points[u][0] - points[v][0]) + abs(points[u][1] - points[v][1]);
if (d < dist[v]) dist[v] = d;
}
}
return cost;
}
};function minCostConnectPoints(points) {
const n = points.length;
const dist = new Array(n).fill(Infinity);
const inTree = new Array(n).fill(false);
dist[0] = 0;
let cost = 0;
for (let k = 0; k < n; k++) {
let u = -1;
for (let i = 0; i < n; i++)
if (!inTree[i] && (u === -1 || dist[i] < dist[u])) u = i;
inTree[u] = true;
cost += dist[u];
for (let v = 0; v < n; v++) {
if (inTree[v]) continue;
const d = Math.abs(points[u][0] - points[v][0]) + Math.abs(points[u][1] - points[v][1]);
if (d < dist[v]) dist[v] = d;
}
}
return cost;
}Edge cases to test
- A single point: the cost is 0
- Two points: the cost is just their distance
- Points on one line: the cheapest links join each point to its neighbour
- Many links with equal cost: any choice among equal links gives the same total
- Negative coordinates: the distance uses absolute differences, so the sign does not matter
- The cheapest link out of a point is not always in the answer if it would close a loop; a greedy that only looks at each point's nearest neighbour can leave the points split into separate groups
Hints
Hint 1
Think of every point as a node and every pair of points as an edge whose weight is their Manhattan distance. You want the cheapest set of edges that connects all nodes.
Hint 2
Such a set never contains a cycle (dropping one edge of a cycle keeps everything connected and costs less), so it is a tree with n - 1 edges: a minimum spanning tree.
Hint 3
Kruskal: sort all edges by weight and keep each edge that joins two different groups, using union-find to track the groups. Prim: grow one tree from point 0, always adding the outside point that is closest to the tree.
Hint 4
The graph is complete, with about n^2 / 2 edges. Prim with a plain array of best distances runs in O(n^2) and needs no edge list at all.
FAQ
What is the best time complexity for Min Cost to Connect All Points?
Optimal (Prim with an array of best distances) runs in O(n^2) time and O(n) extra space. Each of the n rounds makes two scans over n points.
Which pattern does Min Cost to Connect All Points use?
It is a graphs problem that uses the minimum spanning tree pattern. Other problems with the same pattern: Connecting Cities With Minimum Cost.
Is there a brute force solution for Min Cost to Connect All Points?
Yes. Brute force (grow the tree, scanning every pair) takes O(n^3) time and O(n) space. Start a tree with point 0.
Which edge cases should I test for Min Cost to Connect All Points?
A single point: the cost is 0; Two points: the cost is just their distance; Points on one line: the cheapest links join each point to its neighbour; Many links with equal cost: any choice among equal links gives the same total; Negative coordinates: the distance uses absolute differences, so the sign does not matter; The cheapest link out of a point is not always in the answer if it would close a loop; a greedy that only looks at each point's nearest neighbour can leave the points split into separate groups.