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?- A. 2 2
- B. 2 -1
- C. 1 -1
- 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
- Problem: A tree on nodes 1..n received one extra edge. Return the LAST edge in the input whose removal leaves a tree (union-find). python…
- Problem: Replace each word of a sentence by its shortest root from a dictionary (if any root is a prefix). python def replace(roots…
- Problem: Find the shortest palindrome obtainable by adding characters only in FRONT of s, using the KMP failure function of s + '#' +…
- Problem: Is s made of one substring repeated two or more times? Trick: check whether s occurs in (s + s) with the first and last…
- Problem: Delete the fewest characters so that no two letters have the same (nonzero) frequency. python from collections import Counter def…
- Problem: An array of n + 1 integers holds values 1..n with exactly one value repeated (possibly several times). Find it in O(1) extra…