Min Cost to Connect All Points
LeetCode 1584 · Medium · solution, intuition & step-by-step walkthrough
Kruskal: sorted edges + union-find.
This is how I solved Min Cost to Connect All Points (LeetCode 1584), a medium problem from the Minimum Spanning Tree pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Connecting every point as cheaply as possible is a minimum spanning tree. Kruskal's algorithm sorts all candidate edges by Manhattan distance and adds each one that connects two different components, tracked by a disjoint set.
Approach
- 1
Build every pair's Manhattan distance.
- 2
Sort edges by weight.
- 3
Union endpoints in different components and add the weight.
How I solved it
Kruskal + DSUPythonO(n² log n) time
class DisjointSet:
def __init__(self,n):
self.rank = [0]*(n+1)
self.parents = [i for i in range(n+1)]
def find(self,u):
if self.parents[u]==u:
return u
self.parents[u]=self.find(self.parents[u])
return self.parents[u]
def union(self,u,v):
ulp_u,ulp_v = self.find(u),self.find(v)
if ulp_u==ulp_v:
return
if self.rank[ulp_u]<self.rank[ulp_v]:
self.parents[ulp_u]=ulp_v
elif self.rank[ulp_v]<self.rank[ulp_u]:
self.parents[ulp_v]=ulp_u
elif self.rank[ulp_v]==self.rank[ulp_u]:
self.parents[ulp_v]=ulp_u
self.rank[ulp_u]+=1
class Solution:
def minCostConnectPoints(self, points: List[List[int]]) -> int:
n= len(points)
ds = DisjointSet(n)
edges = []
for i in range(n):
for j in range(i+1,n):
xi,yi = points[i]
xj,yj = points[j]
wt = abs(xi - xj) + abs(yi - yj)
edges.append([wt,i,j])
edges.sort(key=lambda x:x[0])
weight = 0
for w,u,v in edges:
if ds.find(u)!=ds.find(v):
ds.union(u,v)
weight+=w
return weight
Min Cost to Connect All Points — FAQ
What is the intuition behind Min Cost to Connect All Points?
Connecting every point as cheaply as possible is a minimum spanning tree. Kruskal's algorithm sorts all candidate edges by Manhattan distance and adds each one that connects two different components, tracked by a disjoint set.
How do you solve Min Cost to Connect All Points (LeetCode 1584)?
1. Build every pair's Manhattan distance. 2. Sort edges by weight. 3. Union endpoints in different components and add the weight.
What is the time and space complexity of Min Cost to Connect All Points?
Time: O(n² log n). Space: O(n²). (Accepted approach: Kruskal + DSU.)
What are common mistakes in Min Cost to Connect All Points?
Prim's with a heap avoids storing all n² edges.