Skip to content

Redundant Connection

Find the edge that closes the cycle in a tree with one extra edge, using union-find in input order.

MediumUnion-Find
Solve on LeetCode

The problem

A tree with nodes labeled 1 to n had one extra edge added, and you get all n edges as the list edges. Return an edge whose removal turns the graph back into a tree. If several edges work, return the one that appears last in edges.

Input edges = [[1, 2], [2, 3], [3, 4], [2, 4], [4, 5]]

Output [2, 4]

2, 3 and 4 form a cycle, and [2, 4] is the last of its three edges in the list.

Input edges = [[2, 3], [1, 2], [3, 4], [1, 3]]

Output [1, 3]

Removing any edge of the cycle 1, 2, 3 leaves a tree, and [1, 3] is the one that appears last.

Key constraint: Exactly one edge is extra, so the graph has exactly one cycle, and the answer is one of the edges on it.

How to spot the pattern

  • You must spot the first edge that joins two nodes that are already connected.
  • Edges arrive in order, and all you need is to merge groups and ask whether two nodes share a group.

The idea

Add the edges one by one with union-find. An edge whose two ends are already in the same group joins nodes that are connected anyway, so it closes the cycle. Every other edge on that cycle had to come earlier for the ends to be connected already, so this edge is the cycle edge that appears last, which is exactly the one the problem asks for.

Brute force: Try removing each edge, starting from the last one, and check with a DFS whether the rest is a connected tree, which takes O(n^2) time.

Step by step

  1. 1Make a union-find over the nodes 1 to n, so the arrays need n + 1 entries.
  2. 2Go through edges in order and try to union the two ends of each edge.
  3. 3If the two ends already share a root, return this edge, because it closes the cycle.
  4. 4Otherwise the union merges their groups, and you move on to the next edge.

See the pattern move

The union-find pattern on a small example. Step through it, or press play.

Code

class Solution:
    def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
        n = len(edges)
        parent = list(range(n + 1))  # nodes are numbered 1 to n
        group_size = [1] * (n + 1)

        def find(x: int) -> int:
            while parent[x] != x:
                parent[x] = parent[parent[x]]  # path halving: point to the grandparent
                x = parent[x]
            return x

        def union(x: int, y: int) -> bool:
            a, b = find(x), find(y)
            if a == b:
                return False  # already one group
            if group_size[a] < group_size[b]:
                a, b = b, a
            parent[b] = a  # hang the smaller group under the larger one
            group_size[a] += group_size[b]
            return True

        for a, b in edges:
            if not union(a, b):
                return [a, b]  # a and b were already joined: this edge closes the cycle
        return []

Complexity

Time

O(n)

Space

O(n)

Each edge costs one find and maybe one union, both nearly O(1) with path compression and union by size; the arrays hold n + 1 entries.

Watch out for

  • Sizing the arrays as n when the nodes are numbered 1 to n; they need n + 1 entries.
  • Returning the first edge of the cycle instead of the edge that closes it, which is the last cycle edge in the input.
  • Checking whether the two nodes are directly linked instead of whether their roots match.

Follow-up questions

What if the graph is directed, a rooted tree plus one extra edge?

Then one node may end up with two parents, and that case needs extra handling: try each of its two incoming edges as the answer and use union-find to see which removal leaves no cycle. That is Redundant Connection II.

How would you list every edge on the cycle?

Build the tree from all the other edges, then find the path between the two ends of the returned edge with a DFS. That path plus the edge is the cycle.

In Hinglish

Edges ek ek karke union-find mein jodo. Jis edge ke dono sire pehle se ek hi group mein hon, wahi cycle band kar rahi hai, use return karo.

Related problems