Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Each move removes either the leftmost or the rightmost box and subtracts its weight from x. Find the minimum moves to make x exactly 0 (−1 if impossible). Equivalent: the longest middle block with sum total − x.

Problem: Each move removes either the leftmost or the rightmost box and subtracts its weight from x. Find the minimum moves to make x exactly 0 (−1 if impossible). Equivalent: the longest middle block with sum total − x.
def min_ops(a, x):
    target = sum(a) - x
    if target < 0: return -1
    l = run = 0; best = -1
    for r, v in enumerate(a):
        run += v
        while run > target:
            run -= a[l]; l += 1
        if run == target:
            best = max(best, r - l + 1)
    return -1 if best == -1 else len(a) - best
print(min_ops([2, 3, 1, 1, 4, 2], 6), min_ops([4, 2, 9, 1, 3], 8), min_ops([1, 1], 3))
What is printed?
  1. A. 2 3 -1
  2. B. 3 3 -1
  3. C. 2 2 -1
  4. D. 2 3 2

Correct answer: A. 2 3 -1

Whatever is removed from the two ends, what remains is a contiguous middle block of sum total − x, so maximise its length with a positive-value sliding window. [2, 3, 1, 1, 4, 2]: total 13, target 7; the block 2, 3, 1, 1 (length 4) remains → remove 4 and 2 → 2 moves. [4, 2, 9, 1, 3]: target 11 = 2 + 9 → remove 4, 1, 3 → 3 moves. Greedily removing the larger end does not work in general (it can overshoot). O(n).

More Coding Interview Problems questions

Exams that ask this topic