#685
Redundant Connection II
HardDepth-First SearchBreadth-First SearchUnion-FindGraph TheoryUnion-FindGraph Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a Union-Find (Disjoint Set Union) data structure to efficiently manage and check cycles in the graph. We can keep track of the parent of each node and detect if adding an edge creates a cycle.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a parent array to keep track of the parent of each node.
- 2Step 2: Iterate through each edge and try to union the nodes. If both nodes already have a parent, mark this edge as a candidate for removal.
- 3Step 3: If a cycle is detected during the union operation, return the last edge that caused the cycle.
solution.py13 lines
1def findRedundantDirectedConnection(edges):
2 parent = [0] * (len(edges) + 1)
3 def find(x):
4 if parent[x] == 0:
5 return x
6 parent[x] = find(parent[x])
7 return parent[x]
8 for u, v in edges:
9 pu, pv = find(u), find(v)
10 if pu == pv:
11 return [u, v]
12 parent[pu] = pv
13 return []ℹ
Complexity note: The time complexity is O(n) because we perform a union-find operation for each edge, which is efficient due to path compression. The space complexity is O(n) for the parent array.
- 1Using Union-Find helps efficiently detect cycles in directed graphs.
- 2Understanding the properties of trees is crucial for solving graph-related problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.