Data Structures & AlgorithmsVery hardProduct company OA
Problem: a ring of n stalls holds 1 (occupied) or 0 (free). In one swap you exchange any two stalls. Find the minimum swaps to bring all occupied stalls together somewhere on the ring: slide a window of length ones = total 1s over the doubled array and count the 0s it contains.
Problem: a ring of n stalls holds 1 (occupied) or 0 (free). In one swap you exchange any two stalls. Find the minimum swaps to bring all occupied stalls together somewhere on the ring: slide a window of length ones = total 1s over the doubled array and count the 0s it contains.
def min_swaps(a):
ones = sum(a); n = len(a)
if ones == 0: return 0
b = a + a
zeros = ones - sum(b[:ones]); best = zeros
for i in range(ones, n + ones):
zeros += (b[i] == 0) - (b[i - ones] == 0)
best = min(best, zeros)
return best
def linear_only(a):
ones = sum(a)
return min(a[i:i + ones].count(0) for i in range(len(a) - ones + 1))
r = [1, 0, 1, 1, 0, 0, 1, 0, 1]
print(min_swaps(r), linear_only(r), min_swaps([0, 1, 0, 1, 1, 0, 0]))- A. 2 2 1
- B. 1 1 1
- C. 2 1 0
- D. 1 2 1
Correct answer: D. 1 2 1
Any final block of k = (number of 1s) consecutive stalls needs exactly as many swaps as it contains 0s (each swap brings in one 1 from outside). So the answer is the minimum number of zeros over all length-k windows of the RING – doubling the array lets windows wrap around. Here k = 5: the wrapping window of stalls 8, 0, 1, 2, 3 holds 1, 1, 0, 1, 1 – a single 0 – while every non-wrapping window holds at least two 0s. For [0, 1, 0, 1, 1, 0, 0] (k = 3) the windows 1, 0, 1 and 0, 1, 1 each hold one 0, so 1 swap. O(n).
More Coding Interview Problems questions
- Problem: a stream of n = 2·10⁵ latencies; after each arrival report the median of the last k = 10⁵ values (sliding window median), time…
- Problem: A scoreboard calls a reading a 'leader' if it is strictly greater than every reading to its right (the last reading is always a…
- Problem: Return the squares of a sorted array (values may be negative) in non-decreasing order in O(n), filling the result from the back…
- Problem: A wallet starts with a positive balance s and then applies the day's changes in order. Find the minimum s such that the running…
- Problem: A warehouse aisle has shelves with weights; find the leftmost 'balance shelf' i such that the total weight strictly to its left…
- Problem: A street has n = 6 lamps, all starting at brightness 0. Each command (l, r, v) adds v to every lamp from l to r (0-based…