Redundant Connection II (LeetCode 685): Solution and Explanation

Hard
Depth First Search
Breadth First Search
Union Find
Graph

A rooted tree had one extra directed edge added, so now the graph either has a node with two parents, a cycle, or both. Return the edge that can be removed to turn it back into a rooted tree, choosing the one that appears last in the input when several qualify.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

In the undirected version, the first edge that closes a cycle is the answer. Directions make it harder, because a valid rooted tree also requires every node except the root to have exactly one parent. The extra edge can break the tree in three ways: it can point into a node that already has a parent, it can close a directed cycle back into the root, or it can do both at once.

So first look for a node with two incoming edges. If one exists, call the earlier edge candidate1 and the later one candidate2; the answer must be one of them. Then run union-find over all edges while pretending candidate2 does not exist. If the remaining edges form no cycle, removing candidate2 produced a valid tree, and since it is later in the input, it is the answer. If a cycle still appears, then candidate2 was not the problem and candidate1 is the edge on the cycle that must go.

If no node has two parents, the extra edge pointed into the root and created a cycle, which is exactly the undirected case. The edge that first closes a cycle during union-find is the answer, matching the rule to return the last valid candidate.

Approach: Two-parent detection plus union-find

  1. Walk the edges and record each node's parent. When a node already has one, save candidate1 = [old parent, v] and candidate2 = [u, v].
  2. Initialize a union-find array root over nodes 1 to n with path compression in find.
  3. Process edges again, skipping candidate2 if it exists.
  4. For each other edge, if find(u) == find(v), a cycle exists: return candidate1 if there was a two-parent node, otherwise return this edge.
  5. Otherwise union the two sets with root[pu] = pv.
  6. If no cycle appears, return candidate2.

Step-by-step example

edges = [[2,1],[3,1],[4,2],[1,4]]
  1. Node 1 gets parent 2 first, then edge [3,1] gives it a second parent, so candidate1 = [2,1] and candidate2 = [3,1].
  2. Union-find pass: [2,1] joins 2 and 1. [3,1] is skipped.
  3. [4,2] joins 4 into the set containing 2 and 1.
  4. [1,4]: 1 and 4 already share a root, so there is a cycle 1 to 4 to 2 to 1.
  5. Because a two-parent node exists, return candidate1 = [2,1]. Removing it leaves 3 to 1 to 4 to 2, a valid tree rooted at 3.

Code: Python, Java, C++

1class Solution:
2    def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]:
3        n = len(edges)
4        parent = [0] * (n + 1)
5        candidate1, candidate2 = None, None
6
7        # Find node with two parents
8        for u, v in edges:
9            if parent[v] != 0:
10                candidate1 = [parent[v], v]
11                candidate2 = [u, v]
12            else:
13                parent[v] = u
14
15        # Union-Find
16        root = list(range(n + 1))
17        def find(x):
18            if root[x] != x:
19                root[x] = find(root[x])
20            return root[x]
21
22        for u, v in edges:
23            if candidate2 and u == candidate2[0] and v == candidate2[1]:
24                continue  # Skip candidate2
25            pu, pv = find(u), find(v)
26            if pu == pv:  # Cycle found
27                return candidate1 if candidate1 else [u, v]
28            root[pu] = pv
29
30        return candidate2

Time and space complexity

Time

O(n log n)

Each pass touches every edge once. With path compression but no union by rank, each find costs O(log n) amortized, which is effectively constant in practice.

Space

O(n)

The parent array and the union-find array each hold n + 1 entries.

Other approaches

Try removing each edge from the end (time O(n²), space O(n))

For each edge from last to first, remove it and check whether the rest forms a rooted tree: exactly one root, every other node with one parent, and all nodes reachable. Simple but quadratic.

DFS cycle detection (time O(n), space O(n))

After finding the two-parent candidates, build the parent pointers without candidate2 and walk up from any node to detect a cycle, instead of using union-find.

Common mistakes

  • Treating it like the undirected version and returning the first edge that closes a cycle. That fails when a node has two parents but no cycle.
  • Skipping candidate1 instead of candidate2 during the union pass. The later edge is preferred, so it is the one you test removing first.
  • Returning the cycle edge found during union when a two-parent node exists. In that case the answer is candidate1, not the edge where the cycle was noticed.
  • Allocating arrays of size n instead of n + 1. Nodes are labeled 1 to n.

Frequently asked questions

What is the difference between Redundant Connection and Redundant Connection II?

The first is undirected, so any cycle-closing edge works. The second is directed, so you must also handle a node with two parents, which leads to three distinct cases.

What are the three cases in Redundant Connection II?

A node has two parents and there is no cycle, a cycle exists with no two-parent node, or both happen together. Each case selects a different edge to remove.

Why skip candidate2 during union-find?

Because it appears later, it is the preferred answer. If the graph is valid without it, return it; if a cycle remains, the other candidate must be the culprit.

What is the time complexity of Redundant Connection II?

Near-linear: two passes over n edges with union-find operations that cost O(log n) amortized each with path compression.