|
| 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