Redundant Connection II

Hard

Topics
GraphUnion FindTreeDFS

A rooted tree is a directed graph where every node has exactly one parent except the root, which has none. You start with such a tree on n nodes labelled 1 to n and add one extra directed edge.

Given the resulting edges list, where edges[i] = [u, v] is a directed edge from parent u to child v, return the edge that can be removed so the remaining graph is a rooted tree of n nodes. If several answers exist, return the one that appears last in the input.

Example 1

123
node with two parents
A rooted tree allows one parent per node and no cycle, and the extra directed edge breaks one or both rules. Node 3 has two incoming arrows, so the edge to remove is one of those two — whichever still leaves the rest acyclic.
Directed edges [parent, child] over nodes 1..n.
Input:  edges = [[1,2],[1,3],[2,3]]
Output: [2,3]
Explanation: Node 3 has two parents. Removing the later of the two edges into it leaves a valid rooted tree.

Example 2

12345
No node has two parents, so the only fault is a cycle and the answer is the last edge that closes it.
Input:  edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]
Output: [4,1]
Explanation: Every node has one parent, so the fault is a cycle. Removing the edge that closes it restores the tree.

Constraints

  • n == edges.length
  • 3 <= n <= 1000
  • edges[i].length == 2
  • 1 <= u, v <= n
  • u != v
Editorial — intuition, approach, complexity and pitfalls

Intuition

Adding one directed edge to a rooted tree breaks it in exactly one of two ways: some node ends up with two parents, or the graph gains a cycle while every node still has one parent. Both can happen at once — the extra edge creates a second parent and closes a cycle — and that overlap is the whole difficulty. Detect the two-parent case first, then let union-find decide which of the two candidate edges to discard.

Approach

  1. Scan the edges and record a parent for each child. If a child already has one, remember the two competing edges as first (the earlier one) and second (the later one).
  2. If no node has two parents, run union-find over all edges and return the first edge whose endpoints are already connected — that edge closes the cycle.
  3. If a node does have two parents, run union-find again but skip second. If all remaining unions succeed, the graph without second is a valid tree, so return second.
  4. If skipping second still leaves a cycle, then first is the edge tangled up in it, so return first instead.
class Solution:
    def findRedundantDirectedConnection(self, edges):
        n = len(edges)
        parent_of = {}
        first = second = None
        for u, v in edges:
            if v in parent_of:
                first = [parent_of[v], v]
                second = [u, v]
            else:
                parent_of[v] = u

        root = list(range(n + 1))

        def find(x):
            while root[x] != x:
                root[x] = root[root[x]]
                x = root[x]
            return x

        for u, v in edges:
            if second is not None and [u, v] == second:
                continue
            ru, rv = find(u), find(v)
            if ru == rv:
                return first if second is not None else [u, v]
            root[rv] = ru
        return second

Dry Run

Two different defects are possible, and they need different answers, so the
solution asks two questions in two passes.
edges = 1->2, 1->3, 2->3
pass 1 -- does any node have two parents?
  edge 1->2   parent_of[2] = 1
  edge 1->3   parent_of[3] = 1
  edge 2->3   3 already has parent 1, so record both candidates
              first = [1,3]   second = [2,3]
pass 2 -- union every edge EXCEPT second, and see whether a cycle survives.
  edge 1->2   find(1)=1 find(2)=2   roots differ, union[1]=2
  edge 1->3   find(1)=2 find(3)=3   roots differ, union[2]=3
  edge 2->3   skipped, it is second
  no cycle survived, so removing second was enough          answer 2 3
Now the other branch of the same code, on edges = 2->1, 3->1, 4->2, 1->4:
  pass 1  parent_of[1] = 2, then 3->1 collides   first = [2,1]  second = [3,1]
  pass 2  2->1 union[2]=1 ; 3->1 skipped ; 4->2 union[4]=1
          1->4  find(1)=1 find(4)=1  same root -- a cycle is still there
          second was load-bearing, so the other candidate is the culprit
                                                            answer 2 1
And when no node has two parents the only possible defect is a plain cycle, so the
edge that closes it is the answer: on 1->2, 2->3, 3->4, 4->1, 1->5 the unions run
1,2,3 and then 4->1 finds find(4) = find(1) = 4, and with first still None the
cycle-closing edge itself is returned -- answer 4 1.
Skipping second during pass 2 is the trick that lets one union-find pass settle
both questions at once.

Complexity

  • Time — O(n a(n)) — two linear scans with near-constant union-find operations.
  • Space — O(n) for the parent map and union-find roots.

Common Pitfalls

  • Returning second unconditionally in the two-parent case is the classic wrong answer. When first also lies on a cycle, removing second leaves the cycle intact.
  • Comparing candidate edges by value can misfire if the input repeats a pair. Track the index instead when duplicates are possible.
  • This is not Redundant Connection with a direction bolted on. The undirected version only ever has the cycle case, so plain union-find is not sufficient here.
  • Labels run from 1 to n, so size the union-find array n + 1 or you will read out of bounds.

Full Solution — all languages

class Solution:
    def findRedundantDirectedConnection(self, edges):
        n = 0
        for u, v in edges:
            n = max(n, u, v)
        parent_of = {}
        first = second = None
        for u, v in edges:
            if v in parent_of:
                first = [parent_of[v], v]
                second = [u, v]
            else:
                parent_of[v] = u

        union = list(range(n + 1))

        def find(x):
            while union[x] != x:
                union[x] = union[union[x]]
                x = union[x]
            return x

        for u, v in edges:
            if second is not None and u == second[0] and v == second[1]:
                continue
            a, b = find(u), find(v)
            if a == b:
                return first if first is not None else [u, v]
            union[a] = b
        return second
SensAI
Beta
Tap the mic to stop voice mode