Uber · Question 43 · Graphs
Find Redundant Connection
Problem
In a graph that started as a tree with n nodes, one extra edge is added, making it have a cycle. Given edges, find the edge that can be removed so that the resulting graph is a tree of n nodes. If multiple answers, return the one that appears last.
Approach
Use Union - Find. Iterate edges; for each edge (u, v), check if u and v already share the same root; if yes, that edge is redundant. Otherwise union them.
Time O(E×α(n))Space O(n)
How it works
- 1Union edges one by one.
- 2The first edge joining same-root nodes is redundant.
Sample input / output
Input: 3 1 2 1 3 2 3 Output: [2, 3]
Constraints
n == edges.length; 3 <= n <= 1000; 1 <= ai, bi <= n.
Solution — read it, then walk it
Time O(E×α(n))Space O(n)Loops 1Branches 7Returns 5source · Python
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/34
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits