Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 576ef50

Browse files
Create 684.py
1 parent b465df8 commit 576ef50

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

‎500-1000/684.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution(object):
2+
def findRedundantConnection(self, edges):
3+
"""
4+
:type edges: List[List[int]]
5+
:rtype: List[int]
6+
"""
7+
n = len(edges)
8+
parent = [i for i in range(n + 1)] # Initialize each node as its own parent
9+
rank = [0] * (n + 1) # Rank for union by rank
10+
11+
def find(i):
12+
if parent[i] != i:
13+
parent[i] = find(parent[i]) # Path compression
14+
return parent[i]
15+
16+
def join(u, v):
17+
rootU = find(u)
18+
rootV = find(v)
19+
20+
if rootU != rootV:
21+
# Union by rank
22+
if rank[rootU] > rank[rootV]:
23+
parent[rootV] = rootU
24+
elif rank[rootU] < rank[rootV]:
25+
parent[rootU] = rootV
26+
else:
27+
parent[rootV] = rootU
28+
rank[rootU] += 1
29+
30+
for u, v in edges:
31+
if find(u) == find(v):
32+
return [u, v] # Cycle detected
33+
join(u, v) # Merge sets
34+
35+
return [] # Unreachable for valid inputs

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /