← Uber bank

Uber · Question 43 · Graphs

Find Redundant Connection

GraphsPythoncode⏱ O(E×α(n))💾 O(n)
Product-based

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

  1. 1Union edges one by one.
  2. 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.
yesnoyesnoyesnoyesnoyes↻ repeatyesnoSTARTedgesn = len(edges)parent = list(range(n + 1))rank = [0] * (n + 1)DEFINE find(x)if parent[x] != xparent[x] = find(parent[x])RETURN parent[x]DEFINE union(a, b)ra, rb = find(a), find(b)if ra == rbRETURN Falseif rank[ra] < rank[rb]parent[ra] = rbelif rank[ra] >rank[rb]parent[rb] = raELSEparent[rb] = rarank[ra] += 1RETURN Truefor u, v in edgesif not union(u, v)RETURN [u, v]RETURN []DEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)e = int(next(it))edges = [[int(next(it)),int(next(it))] for _ inrange(e)]print(findRedundantConnection(edges))if __name__ =="__main__"main()END
  • 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