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?- A. 2 3 -1
- B. 3 3 -1
- C. 2 2 -1
- 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
- Problem: A speech-analysis tool reports the maximum number of vowels in any window of exactly k consecutive letters. python def…
- Problem: Move all zero readings to the end of the array in place while keeping the order of the non-zero readings. python def…
- Problem: In a text editor '#' means backspace (on an empty buffer it does nothing). Compute the final text with a stack. python def…
- Problem: Normalise a Unix-style absolute path: collapse repeated slashes, drop '.', and let '..' go up one directory (never above root)…
- Problem: Find the minimum number of brackets to insert so that a string of '(' and ')' becomes balanced. python def minadd(s): open = add…
- Problem: Parcels 1..5 are pushed onto a loading stack in that order (pops may happen at any time). Decide whether a given pop order is…