Data Structures & AlgorithmsHardProduct company OA

Problem: n computers and a list of cables; you may unplug any cable and reconnect it between any two computers. Minimum moves to connect everything (−1 if impossible).

Problem: n computers and a list of cables; you may unplug any cable and reconnect it between any two computers. Minimum moves to connect everything (−1 if impossible).
def ops_to_connect(n, cables):
    if len(cables) < n - 1: return -1
    p = list(range(n))
    def find(x):
        while p[x] != x: p[x] = p[p[x]]; x = p[x]
        return x
    comps = n
    for a, b in cables:
        ra, rb = find(a), find(b)
        if ra != rb: p[ra] = rb; comps -= 1
    return comps - 1
print(ops_to_connect(6, [(0, 1), (1, 2), (0, 2), (3, 4), (2, 1)]), ops_to_connect(6, [(0, 1), (1, 2), (3, 4)]), ops_to_connect(5, [(0, 1), (1, 2), (2, 0), (0, 3), (3, 1)]))
What is printed?
  1. A. 2 -1 1
  2. B. 2 3 1
  3. C. 3 -1 1
  4. D. 2 -1 2

Correct answer: A. 2 -1 1

With at least n − 1 cables there are always enough redundant ones, so the answer is (components − 1). First: components {0, 1, 2}, {3, 4}, {5} → 2 moves (cables (0, 2) and the duplicate (2, 1) are spare). Second: only 3 cables for 6 machines → −1 regardless of layout. Third: {0, 1, 2, 3} and {4} → 1. O(E·α(n)).

More Coding Interview Problems questions

Exams that ask this topic