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

Problem: 8 servers are joined by cables one at a time. Count the connected groups at the end and how many cables were redundant (joined two servers already connected).

Problem: 8 servers are joined by cables one at a time. Count the connected groups at the end and how many cables were redundant (joined two servers already connected).
def run(n, edges):
    par = list(range(n))
    def find(x):
        while par[x] != x:
            par[x] = par[par[x]]
            x = par[x]
        return x
    comps, red = n, 0
    for u, v in edges:
        ru, rv = find(u), find(v)
        if ru == rv:
            red += 1
        else:
            par[ru] = rv; comps -= 1
    return comps, red
c, r = run(8, [(6,2),(5,0),(2,5),(7,2),(6,6),(2,3),(0,4),(2,2),(1,2)])
print(c, r)
What is printed?
  1. A. 1 1
  2. B. 1 0
  3. C. 2 2
  4. D. 1 2

Correct answer: D. 1 2

Tracing union-find with path compression over the edges in order (a self-loop (x, x) always counts as redundant since find(x) == find(x)) gives 1 final components and 2 redundant cables.

More Coding Interview Problems questions

Exams that ask this topic