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?- A. 2 -1 1
- B. 2 3 1
- C. 3 -1 1
- 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
- Problem: Given equations like "a==b" and "b!=c" over single-letter variables, can all hold at once? Union all '==' pairs first, then check…
- Problem: A 3-wheel lock starts at "000"; each move turns one wheel by ±1 (9 wraps to 0). Some codes are dead (the lock jams). Find the…
- Problem: Shortest paths from node 1 in a weighted DAG (negative edges allowed): topologically sort with Kahn's algorithm, then relax edges…
- Problem: An investor starts with capital w and may finish at most k projects; project i needs capital[i] to start and adds profits[i] when…
- Problem: A single CPU receives tasks (enqueue time, duration). When idle it starts the available task with the shortest duration (ties…
- Problem: Walk along buildings of given heights; climbing up by d needs d bricks or one ladder (going down is free). Return the furthest…