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

Problem: Return the shortest subarray with sum at least k when values can be negative (monotonic deque over prefix sums).

Problem: Return the shortest subarray with sum at least k when values can be negative (monotonic deque over prefix sums).
from collections import deque
def shortest(a, k):
    P = [0]
    for x in a: P.append(P[-1] + x)
    dq, best = deque(), float('inf')
    for i, p in enumerate(P):
        while dq and p - P[dq[0]] >= k:
            best = min(best, i - dq.popleft())
        while dq and P[dq[-1]] >= p:
            dq.pop()
        dq.append(i)
    return best if best != float('inf') else -1
print(shortest([2, -1, 2], 3), shortest([1, 2], 4), shortest([84, -37, 32, 40, 95], 167))
What is printed?
  1. A. 3 -1 3
  2. B. 2 -1 3
  3. C. 3 -1 5
  4. D. 3 0 3

Correct answer: A. 3 -1 3

Keep prefix indices with increasing prefix sums; a front index that already satisfies P[i] − P[j] ≥ k can never give a shorter answer later, so pop it. [2, −1, 2] needs all three. [32, 40, 95] = 167 is length 3. The variable sliding window fails here because of negatives. O(n).

More Coding Interview Problems questions

Exams that ask this topic