Redundant Connection II solution explained
Redundant Connection II gives you a directed graph that was a rooted tree until one extra edge was added, and asks which edge to delete so it becomes a rooted tree again, preferring the edge that comes last in the input. The extra edge either gives some node two parents, closes a cycle, or does both. Detect a node with two parents, then use union-find on the remaining edges to decide which candidate to drop, in O(n α(n)) time.
By Evin JohnPublished 9 min read
The problem in plain words
Nodes are labelled 1 to n. Someone started with a rooted tree: every node except the root had exactly one parent edge pointing to it, and every node could be reached from the root. Then they added one more directed edge between two different nodes that were not already joined by an edge. You receive all n edges as [parent, child] pairs. Return an edge whose removal turns the graph back into a rooted tree. When more than one edge would work, return the one that appears latest in the list.
| Edges | Answer | Case |
|---|---|---|
| [2,1], [2,3], [3,4], [1,4] | [1,4] | Node 4 has two parents (3 and 1) and there is no cycle, so drop the later parent edge |
| [2,3], [4,1], [3,4], [1,2] | [1,2] | Every node has one parent, but 4, 1, 2, 3 form a loop. Any loop edge works, and [1,2] is the last in the list |
| [1,2], [2,3], [3,4], [4,2] | [4,2] | Node 2 has parents 1 and 4, and 2, 3, 4 form a loop. [4,2] is the later parent edge and also on the loop |
| [4,2], [2,3], [3,4], [1,2] | [4,2] | The same graph reordered. Removing [1,2] would leave the loop, so the earlier parent edge [4,2] is the only fix |
The last two rows are the heart of the problem. The "return the last one" rule only chooses between edges that actually work. When a node has two parents and a cycle also exists, only the parent edge on the cycle is a valid removal, wherever it sits in the list.
What the interviewer is checking
The undirected version of this problem is a one-pass union-find exercise. The directed version punishes anyone who reuses that code unchanged, because a node with two parents is a problem even without a cycle. The interviewer wants you to list the cases before coding, explain how each one breaks the tree rules, and pick the removal that fixes every broken rule at once. Clear case analysis is worth more here than speed.
Brute force: try each removal from the back
Since the latest valid edge wins, walk the list from the end. For each edge, pretend it is gone and test whether the rest is a rooted tree: exactly one node with no parent, every other node with exactly one parent, and every node reachable from that root. The first edge that passes is the answer. Each test is O(n), so the total is O(n²).
def redundant_directed_slow(edges):
n = len(edges)
def is_rooted_tree(kept):
parent_count = [0] * (n + 1)
children = [[] for _ in range(n + 1)]
for p, c in kept:
parent_count[c] += 1
children[p].append(c)
roots = [v for v in range(1, n + 1) if parent_count[v] == 0]
if len(roots) != 1 or any(parent_count[v] > 1 for v in range(1, n + 1)):
return False
seen = {roots[0]}
stack = [roots[0]]
while stack:
for c in children[stack.pop()]:
if c not in seen:
seen.add(c)
stack.append(c)
return len(seen) == n
for skip in range(n - 1, -1, -1):
if is_rooted_tree(edges[:skip] + edges[skip + 1:]):
return edges[skip]The three cases
- Two parents, no cycle. The extra edge points at a node that already had a parent, and does not close a loop. Removing either parent edge leaves a valid tree, so the rule picks the one that appears later.
- Cycle, no node with two parents. The extra edge points at the root. The root now has a parent, so every node has exactly one, and following parents goes round in a loop through the root. Removing any loop edge restores a tree, and the rule picks the loop edge that appears last.
- Two parents and a cycle. The extra edge points at a non-root node and also closes a loop. Of the two parent edges into that node, only the one on the loop is a valid removal. Dropping the other still leaves the loop.
Optimal: candidates plus union-find
First pass: record each node's parent. If a node gets a second parent, keep both edges as candidates: first is the edge seen earlier, second is the edge seen later. Second pass: feed every edge except second into a union-find, treating edges as undirected. If some edge joins two nodes that are already connected, a cycle remains. Then decide. If there were no candidates, the cycle edge just found is the answer, and it is the last loop edge in input order because the loop only closes when its final edge arrives. If there were candidates and a cycle still exists without second, the loop must run through first, so return first. If there were candidates and no cycle remains, second is the answer.
def redundant_directed(edges):
n = len(edges)
parent_edge = [None] * (n + 1)
first = second = None
for p, c in edges:
if parent_edge[c] is None:
parent_edge[c] = [p, c]
else: # c now has two parents
first, second = parent_edge[c], [p, c]
group = list(range(n + 1))
def leader(x):
while group[x] != x:
group[x] = group[group[x]] # path halving
x = group[x]
return x
for p, c in edges:
if [p, c] == second:
continue
a, b = leader(p), leader(c)
if a == b: # this edge closes a loop
return first if second else [p, c]
group[b] = a
return secondThe function returns from inside the loop as soon as a cycle shows up, which covers both the cycle-only case and the case where the loop runs through first. If the loop finishes, the graph without second is acyclic, so second must be the extra edge. In the cycle-only case second is None, so the last line is never reached. Union by size or rank is not needed for correctness, and path halving alone is fast enough in practice.
function redundantDirected(edges) {
const n = edges.length;
const parentEdge = new Array(n + 1).fill(null);
let first = null;
let second = null;
for (const e of edges) {
const child = e[1];
if (parentEdge[child] === null) parentEdge[child] = e;
else { first = parentEdge[child]; second = e; }
}
const up = Array.from({ length: n + 1 }, (_, i) => i);
const size = new Array(n + 1).fill(1);
const root = (x) => {
while (up[x] !== x) { up[x] = up[up[x]]; x = up[x]; }
return x;
};
for (const e of edges) {
if (e === second) continue; // same array object, so identity works
let a = root(e[0]), b = root(e[1]);
if (a === b) return second ? first : e;
if (size[a] < size[b]) [a, b] = [b, a];
up[b] = a;
size[a] += size[b];
}
return second;
}Comparing by identity (e === second) is safe in JavaScript because second is the very array taken from the input. In Python the code compares by value, which is also safe because the problem promises no duplicate edges.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Try every removal, latest first | O(n²) | O(n) |
| Candidates plus union-find | O(n α(n)), close to O(n) | O(n) |
| Candidates plus following parent pointers to find the loop | O(n) | O(n) |
The third row avoids union-find: once every node has at most one parent (after setting second aside), you can follow parent pointers from any node and detect a loop with a visited mark. It is equally valid. Union-find is popular because the same code also solves the undirected version.
Edge cases
- n = 2: edges [1,2] and [2,1] form a two-node loop. Either removal works, so the later edge is the answer.
- The extra edge points at the root: no node has two parents. Only the cycle branch can answer.
- Two parent edges where the earlier one is on the loop: only the earlier one works, despite the "last" rule.
- A long chain with the extra edge from the last node back to the first: a loop through all n nodes.
- Edge order shuffled: the answer can change in the cycle-only case, so never sort the edges first.
Common mistakes
- Reusing the undirected solution, which ignores the two-parent case and returns the wrong edge when there is no cycle.
- Always returning the later parent edge when a node has two parents, which fails when the earlier one is on the loop.
- Running union-find on all edges first and only then looking for two parents, which mixes up which cycle edge to report.
- Recording only the child with two parents and forgetting which of its edges came first.
- Sorting or deduplicating edges, which breaks the "last in the input" rule.
Follow-up questions
- Return every edge whose removal works. The brute force already finds them all if you do not stop at the first. With the case analysis: two parents and no loop gives both parent edges, a loop alone gives every loop edge, both gives just one.
- Two extra edges were added. The neat three-case analysis breaks down. Discuss trying each pair of removals, or each single removal followed by the one-edge algorithm, and the cost.
- The graph is undirected. Then only the cycle matters, and the first edge that joins two already-connected nodes is the answer.
How to explain it out loud
Fictional example
- Candidate
- A rooted tree breaks in two ways here: a node gets two parents, or there's a cycle. The extra edge can cause either or both.
- Candidate
- So first I look for a node with two parents and keep both edges, the earlier and the later.
- Interviewer
- And if there are two parents and a cycle?
- Candidate
- Then I leave out the later candidate and run union-find. If a cycle still shows up, the loop goes through the earlier candidate, so that's the one to remove.
- Candidate
- No candidates means the edge points at the root, and the edge that closes the loop is the answer. It's nearly linear overall.
Related problems
Number of Operations to Make Network Connected uses union-find to count components and spare edges in an undirected network. Satisfiability of Equality Equations shows union-find in its simplest form, grouping letters. For ordering problems on directed graphs, see Parallel Courses.
Rehearsing it with Natively
The three-case breakdown is the part interviewers grade, so practice saying it before touching the keyboard. On a Mac or Windows PC, Natively can read an edge list from a screenshot, suggest the candidate-plus-union-find plan, and transcribe your mock explanation so you can check whether you covered the case where the earlier parent edge is the answer. More on that workflow is on the LeetCode practice helper page.
Questions people ask
How do you solve Redundant Connection II?
Look for a node with two parent edges and keep both as candidates. Run union-find on all edges except the later candidate. If a cycle remains, return the earlier candidate, or the cycle edge if there were no candidates; otherwise return the later candidate.
Why is Redundant Connection II harder than the undirected version?
In a directed tree, a node with two parents is invalid even without a cycle, and when both problems occur only the parent edge on the cycle can be removed.
What is the time complexity of Redundant Connection II?
O(n α(n)) with union-find, which is close to linear, and O(n) extra space.
Which edge do you return if several work?
The one that appears last in the input. That rule only chooses among edges whose removal actually leaves a rooted tree.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
