Skip to content

Commit d50076b

Browse files
authored
Create redundant-connection.py
1 parent de8b9bc commit d50076b

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

Python/redundant-connection.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Time: O(nlog*n) ~= O(n), n is the length of the positions
2+
# Space: O(n)
3+
4+
class UnionFind(object):
5+
def __init__(self, n):
6+
self.set = range(n)
7+
self.count = n
8+
9+
def find_set(self, x):
10+
if self.set[x] != x:
11+
self.set[x] = self.find_set(self.set[x]) # path compression.
12+
return self.set[x]
13+
14+
def union_set(self, x, y):
15+
x_root, y_root = map(self.find_set, (x, y))
16+
if x_root == y_root:
17+
return False
18+
self.set[min(x_root, y_root)] = max(x_root, y_root)
19+
self.count -= 1
20+
return True
21+
22+
23+
class Solution(object):
24+
def findRedundantConnection(self, edges):
25+
"""
26+
:type edges: List[List[int]]
27+
:rtype: List[int]
28+
"""
29+
union_find = UnionFind(2000)
30+
for edge in edges:
31+
if not union_find.union_set(*edge):
32+
return edge
33+
return []
34+

0 commit comments

Comments
 (0)