Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: A tree on nodes 1..n received one extra edge. Return the LAST edge in the input whose removal leaves a tree (union-find).

Problem: A tree on nodes 1..n received one extra edge. Return the LAST edge in the input whose removal leaves a tree (union-find).
def redundant(edges):
    par = list(range(len(edges) + 1))
    def f(x):
        while par[x] != x: x = par[x]
        return x
    for a, b in edges:
        ra, rb = f(a), f(b)
        if ra == rb: return [a, b]
        par[ra] = rb
print(redundant([[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]]))
What is printed?
  1. A. [1, 5]
  2. B. [3, 4]
  3. C. [1, 2]
  4. D. [1, 4]

Correct answer: D. [1, 4]

Edges 1–2, 2–3, 3–4 connect 1..4 in a chain; 1–4 then joins two nodes already connected, closing the cycle 1-2-3-4-1. Because union-find processes edges in order, the first edge found inside the cycle is also the last cycle edge in the input.

More Coding Interview Problems questions

Exams that ask this topic