Coding interview problems › Graphs & Grids
🗺️ Graphs & Grids Medium
Min Cost to Connect All Points
Min Cost to Connect All Points explained: a minimum spanning tree over Manhattan distances with Prim's algorithm. Tested Python code and a live MST visual.
Also searched as: minimum spanning tree with Prim's algorithm · Kruskal vs Prim on points with Manhattan distance
Try it live Free
Minimum Spanning Tree: Kruskal vs Prim
In the MST lab, step through Prim growing one tree by always taking the cheapest edge out, and compare it with Kruskal skipping edges that would close a cycle.
Also useful: Union-Find (DSU), Binary Heap & Priority Queue
The problem
Given points on a 2D plane, connecting two points costs their Manhattan distance |x1 - x2| + |y1 - y2|. Return the minimum total cost to connect all points so that every point can reach every other.
The key insight
The cheapest way to connect everything, with no wasted links, is a minimum spanning tree. Every pair of points is a possible edge, so the graph is dense. Prim's algorithm grows one tree from a start point, always adding the cheapest edge leaving the tree; with an O(n²) array version you never even build the edge list.
Step-by-step approach
- Keep
dist[i]= cheapest known cost to attach point i to the tree; start with point 0 at 0, all others at infinity. - Repeat n times: pick the unvisited point with the smallest
dist. - Mark it in the tree and add its
distto the total. - Update every unvisited point's
distwith its Manhattan distance to the newly added point, if smaller. - Return the total.
Python solution
def min_cost_connect_points(points):
n = len(points)
in_tree = [False] * n
dist = [float("inf")] * n # cheapest edge from tree to each point
dist[0] = 0
total = 0
for _ in range(n):
u = min((i for i in range(n) if not in_tree[i]), key=dist.__getitem__)
in_tree[u] = True
total += dist[u]
ux, uy = points[u]
for v in range(n):
if not in_tree[v]:
d = abs(ux - points[v][0]) + abs(uy - points[v][1])
if d < dist[v]:
dist[v] = d
return totalComplexity
Each of the n rounds scans all points once to pick the minimum and once to update distances. That beats Kruskal's O(n² log n) on this complete graph, and needs only O(n) extra arrays.
Common mistakes
- Using Euclidean distance when the problem asks for Manhattan distance.
- Running Dijkstra instead of Prim; Dijkstra minimises distance from the start, not the total edge weight of the tree.
- With Kruskal, forgetting the Union-Find check, so an edge that closes a cycle gets added.
Frequently asked questions
What is the time and space complexity of Min Cost to Connect All Points?
Prim's array version runs in O(n²) time and O(n) space. Kruskal on all n² edges is O(n² log n) time and O(n²) space, so Prim is the better fit for this dense graph.
Kruskal or Prim: which should I use?
Kruskal sorts edges and suits sparse graphs given as an edge list. Prim grows from a node and suits dense graphs, like all pairs of points here.
How is a minimum spanning tree different from shortest paths?
An MST minimises the total weight of edges needed to connect all nodes. Shortest paths minimise the distance from one source to each node; the two trees are usually different.
Preparing for placements?
Take the 2-minute readiness check to find your weak patterns, then follow the placement path from DSA core to system design.
All coding interview problems More Graphs & Grids Graph Search: BFS vs DFS lab Placement prep guides
Problem statements on this site are written in our own words. Problem names are the common names used across interview-prep communities; BitBootcamp is an independent learning platform and is not affiliated with LeetCode or any company that asks these questions.