Redundant Connection
LeetCode 684 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
First edge connecting an already-connected pair.
ನಾನು Redundant Connection (LeetCode 684) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Union Find / DSU ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Add edges one at a time with union-find. The first edge whose two ends are already in the same component closes a cycle — that's the redundant one.
Approach
- 1
DSU over n nodes.
- 2
For each edge, if find(u) == find(v), return it.
- 3
Otherwise union.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
DSUPythonO(n α(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 findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
n = len(edges)
ds = DisjointSet(n)
for u,v in edges:
if ds.find(u)==ds.find(v):
return [u,v]
else:
ds.union(u,v)
Redundant Connection — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Redundant Connection ಹಿಂದಿನ intuition ಏನು?
Add edges one at a time with union-find. The first edge whose two ends are already in the same component closes a cycle — that's the redundant one.
Redundant Connection (LeetCode 684) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. DSU over n nodes. 2. For each edge, if find(u) == find(v), return it. 3. Otherwise union.
Redundant Connection ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(n α(n)). Space: O(n). (Accepted approach: DSU.)
Redundant Connection ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Returning the first such edge matches 'the last one in input order' since only one edge closes the cycle.