Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: n computers and a list of cables. You may unplug any cable and reconnect it elsewhere. Find the minimum number of moves to connect all computers (−1 if impossible).

Problem: n computers and a list of cables. You may unplug any cable and reconnect it elsewhere. Find the minimum number of moves to connect all computers (−1 if impossible).
def moves(n, cables):
    if len(cables) < n - 1: return -1
    par = list(range(n))
    def f(x):
        while par[x] != x: par[x] = par[par[x]]; x = par[x]
        return x
    comps = n
    for a, b in cables:
        ra, rb = f(a), f(b)
        if ra != rb: par[ra] = rb; comps -= 1
    return comps - 1
print(moves(7, [(0,1),(1,2),(2,0),(3,4),(4,5),(5,3)]), moves(6, [(0,1),(0,2),(0,3),(1,2)]))
What is printed?
  1. A. 2 2
  2. B. 2 -1
  3. C. 1 -1
  4. D. 3 -1

Correct answer: B. 2 -1

First case: 6 cables ≥ 6 needed, components {0,1,2}, {3,4,5}, {6} → 2 moves (each triangle has a spare cable). Second: only 4 cables but 5 are needed to join 6 machines, so −1 regardless of layout.

More Coding Interview Problems questions

Exams that ask this topic