Redundant connection
Standard · Write code · about 12 min
A tree with nodes 1 to n got one extra edge, so edges has n edges and exactly one cycle. Return the edge that can be removed to leave a tree. If several edges qualify, return the one that appears last in edges. An empty edges list has no extra edge, so return [].
Example 1
Input:
[[[1,2],[1,3],[2,3]]]
Output:
[2,3]
2-3 arrives when 2 and 3 are already joined through 1.
Example 2
Input:
[[[1,2],[2,3],[3,4],[1,4],[1,5]]]
Output:
[1,4]
Constraints
- 3 ≤ n ≤ 1000, or edges is empty
- edges.length = n
- 1 ≤ u < v ≤ n; no repeated edges
- The graph is connected
Learn the idea first: Union-find applications: connectivity, grouping, redundant edges, a visual lesson.
More Union-find applications: connectivity, grouping, redundant edges problems
- Merge or cycle? Warm-up
- Accounts merge Standard
- Number of provinces Standard