MediumNo. 0684
Redundant Connection — LeetCode 684 Python Solution
- Pattern
- Union-Find
- Topics
- Depth-First Search, Breadth-First Search, Union Find, Graph
- On a study list
- NeetCode 150
- Reading time
- 2 min
- Source
- leetcode.com
The problem
In this problem, a tree is an undirected graph that is connected and has no cycles. You are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added.
Example
- Input
- edges = [[1,2],[1,3],[2,3]]
- Output
- [2,3]
Python solution
class Solution:
def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
def find(x: int) -> int:
if p[x] != x:
p[x] = find(p[x])
return p[x]
p = list(range(len(edges)))
for a, b in edges:
pa, pb = find(a - 1), find(b - 1)
if pa == pb:
return [a, b]
p[pa] = pbComplexity
- Time
- O(n log n)
- Space · auxiliary
- O(n)
Pattern: Union-Find
Merge groups and ask whether two things are connected, both in near-constant time. LeetCode 684. Redundant Connection is filed here because LeetCode tags it Union Find, which is the vocabulary this hub collects.
The union-find guide has the Python template for the pattern and the 83 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0685 | Redundant Connection II | Hard |
| 0399 | Evaluate Division | Medium |
| 0547 | Number of Provinces | Medium |
| 0785 | Is Graph Bipartite? | Medium |
| 0886 | Possible Bipartition | Medium |
| 1319 | Number of Operations to Make Network Connected | Medium |
Frequently asked questions
- How hard is LeetCode 684. Redundant Connection?
LeetCode 684. Redundant Connection is rated Medium on LeetCode.
- What is the time complexity of LeetCode 684. Redundant Connection?
The Python solution on this page runs in O(n log n).
- What is the space complexity of LeetCode 684. Redundant Connection?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 684. Redundant Connection cover?
LeetCode 684. Redundant Connection is tagged Depth-First Search, Breadth-First Search, Union Find and Graph on LeetCode.