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

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

PythonSolution
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] = pb

Complexity

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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.