Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find a redundant edge that, when removed, leaves a tree (return the last such edge in input order).

Problem: Find a redundant edge that, when removed, leaves a tree (return the last such edge in input order).
def redundant(edges):
    p = list(range(len(edges) + 1))
    def f(x):
        while p[x] != x: p[x] = p[p[x]]; x = p[x]
        return x
    for u, v in edges:
        a, b = f(u), f(v)
        if a == b: return [u, v]
        p[a] = b
print(redundant([[1, 2], [1, 3], [2, 3]]), redundant([[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]]))
What is printed?
  1. A. [1, 2] [1, 4]
  2. B. [2, 3] [1, 5]
  3. C. [1, 3] [3, 4]
  4. D. [2, 3] [1, 4]

Correct answer: D. [2, 3] [1, 4]

Add edges one by one; the first edge whose endpoints are already connected closes the cycle, and since a tree plus one edge has exactly one cycle, it is the last cycle edge in input order. Near O(n α(n)).

More Coding Interview Problems questions

Exams that ask this topic