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]))
  1. A. 2 2 1
  2. B. 1 1 1
  3. C. 2 1 0
  4. 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

Exams that ask this topic