Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: n 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 that were already connected).

Problem: n 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 that were 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, [(0,1),(2,3),(1,3),(4,5),(6,6),(5,7),(0,2)])
print(c, r)
What is printed?
  1. A. 3 2
  2. B. 3 1
  3. C. 4 2
  4. D. 2 2

Correct answer: A. 3 2

Groups end as {0,1,2,3}, {4,5,7} and {6}: 3 components. Two cables are redundant: the self-loop (6,6) and (0,2), which arrives after 0 and 2 are already linked through 1–3. Forgetting that a self-loop is redundant gives 1.

More Coding Interview Problems questions

Exams that ask this topic