Number of Operations to Make Network Connected
LeetCode 1319 · Medium · solution, intuition & step-by-step walkthrough
Count extra edges and components with DSU.
This is how I solved Number of Operations to Make Network Connected (LeetCode 1319), a medium problem from the Union Find / DSU pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Every cable that connects two already-connected computers is spare. To join k components you need k − 1 cables, so it's possible exactly when spare cables ≥ components − 1.
Approach
- 1
Union each connection; already connected → extras++.
- 2
Count components.
- 3
required = components − 1; return it if extras suffice, else −1.
How I solved it
DSUPythonO(E α(n)) time
class DisjointSet:
def __init__(self,n):
self.rank = [0]*(n+1)
self.parent = [i for i in range(n+1)]
def find(self,u):
if self.parent[u]==u:
return u
self.parent[u]=self.find(self.parent[u])
return self.parent[u]
def union(self,u,v):
pu,pv = self.find(u),self.find(v)
if pu==pv:
return
if self.rank[pu]<self.rank[pv]:
self.parent[pu]=pv
elif self.rank[pv]<self.rank[pu]:
self.parent[pv]=pu
elif self.rank[pv]==self.rank[pu]:
self.parent[pv]=pu
self.rank[pu]+=1
class Solution:
def makeConnected(self, n: int, connections: List[List[int]]) -> int:
ds = DisjointSet(n)
extras=0
for u,v in connections:
if ds.find(u)==ds.find(v):
extras+=1
else:
ds.union(u,v)
components = 0
for u in range(n):
if ds.parent[u]==u:
components+=1
required = components-1
if required<=extras:
return required
else:
return -1
Number of Operations to Make Network Connected — FAQ
What is the intuition behind Number of Operations to Make Network Connected?
Every cable that connects two already-connected computers is spare. To join k components you need k − 1 cables, so it's possible exactly when spare cables ≥ components − 1.
How do you solve Number of Operations to Make Network Connected (LeetCode 1319)?
1. Union each connection; already connected → extras++. 2. Count components. 3. required = components − 1; return it if extras suffice, else −1.
What is the time and space complexity of Number of Operations to Make Network Connected?
Time: O(E α(n)). Space: O(n). (Accepted approach: DSU.)
What are common mistakes in Number of Operations to Make Network Connected?
Fewer than n − 1 cables total means −1 immediately.