Redundant Connection II
Problem Statement
You get n directed edges [u, v] (an arrow from u to v) on nodes 1 to n. Before one extra arrow was added, the arrows formed a rooted tree: one root that no arrow points into, and every other node has exactly one incoming arrow (its parent), with a path from the root to every node.
Return one arrow that you can remove so that what remains is a rooted tree again. If more than one arrow works, return the one that comes last in the input.
edges: n pairs [u, v], one per arrow, with n = edges.length.
One pair [u, v] from edges: the arrow to remove.
Node 3 has two parents, 1 and 2. Removing 1 → 3 leaves 1 → 2 → 3, a rooted tree. Removing 2 → 3 leaves 1 → 2 and 1 → 3, also a rooted tree. Both work, and 2 → 3 comes later in the input.
No node has two parents, but the arrows 1 → 2 → 3 → 4 → 1 form a cycle, and node 5 hangs off node 1. Removing any cycle arrow leaves a rooted tree. The last one in the input is 4 → 1.
- • n == edges.length
- • 3 ≤ n ≤ 1000
- • edges[i].length == 2
- • 1 ≤ uᵢ, vᵢ ≤ n
- • uᵢ ≠ vᵢ
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Remove arrows from last to first; the first removal that leaves a rooted tree is the answer
Find a node with two parents (A, B); union every edge except B; a cycle left means drop A, otherwise drop B
Remove one arrow at a time, starting from the last. Test what remains: no node has two parents, exactly one node has no parent (the root), and a search from the root reaches all n nodes. The first removal that passes is the answer.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Union-Find (DSU) translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.