Redundant Connection
Problem Statement
A tree is a connected graph with no cycle. Here you get a tree with one extra edge added: n nodes labelled 1 to n, and exactly n edges, so the graph has exactly one cycle.
Return an edge that you can remove so that the rest is still a tree. If more than one edge works, return the one that comes last in the input.
edges: a list of n pairs [a, b], one per edge, with n = edges.length.
One pair [a, b] from edges: the edge to remove.
1–2, 1–3 and 2–3 form a triangle. Removing 1–2 or 1–3 also leaves a tree, but 2–3 comes last in the input.
The cycle is 1–2–3–4–1. Removing 1–2, 2–3 or 3–4 also works, but 1–4 is the last edge of the cycle in the input. Edge 1–5 is not on the cycle.
- • n == edges.length
- • 3 ≤ n ≤ 1000
- • 1 ≤ aᵢ < bᵢ ≤ n
- • There are no repeated edges.
- • The given graph is connected.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Remove edges from last to first; the first removal that leaves a connected graph is the answer
Union the edges in input order; the first edge whose ends already share a root is the answer
Remove one edge at a time, starting from the last edge in the input. After a removal, n − 1 edges remain. Search from node 1: if all n nodes are still reached, what remains is a tree, so the first removal that keeps every node connected 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.