#684
Redundant Connection
MediumDepth-First SearchBreadth-First SearchUnion-FindGraph TheoryUnion-FindGraph Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n α(n)) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n α(n))Space O(n)
The optimal solution uses the Union-Find (Disjoint Set Union) data structure to efficiently detect cycles. By iterating through the edges and attempting to union the nodes, we can quickly determine if adding an edge would create a cycle.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a Union-Find structure to manage connected components.
- 2Step 2: Iterate through each edge in the graph.
- 3Step 3: For each edge, check if the two nodes are already connected using the Union-Find structure.
- 4Step 4: If they are connected, this edge is the redundant one. If not, union the two nodes.
solution.py29 lines
1class UnionFind:
2 def __init__(self, size):
3 self.parent = list(range(size))
4 self.rank = [1] * size
5
6 def find(self, u):
7 if self.parent[u] != u:
8 self.parent[u] = self.find(self.parent[u])
9 return self.parent[u]
10
11 def union(self, u, v):
12 rootU = self.find(u)
13 rootV = self.find(v)
14 if rootU == rootV:
15 return False
16 if self.rank[rootU] > self.rank[rootV]:
17 self.parent[rootV] = rootU
18 elif self.rank[rootU] < self.rank[rootV]:
19 self.parent[rootU] = rootV
20 else:
21 self.parent[rootV] = rootU
22 self.rank[rootU] += 1
23 return True
24
25def findRedundantConnection(edges):
26 uf = UnionFind(len(edges) + 1)
27 for u, v in edges:
28 if not uf.union(u, v):
29 return [u, v]ℹ
Complexity note: The time complexity is O(n α(n)), where α is the Inverse Ackermann function, which grows very slowly, making this approach nearly linear. The space complexity is O(n) due to the storage of the parent and rank arrays.
- 1Using Union-Find is efficient for cycle detection in graphs.
- 2Understanding the properties of trees helps in identifying redundant edges.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.