Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Find the length of the SHORTEST subarray with sum ≥ k when values may be negative (monotonic deque over prefix sums).

Problem: Find the length of the SHORTEST subarray with sum ≥ k when values may 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 j, p in enumerate(P):
        while dq and p - P[dq[0]] >= k:
            best = min(best, j - dq.popleft())
        while dq and P[dq[-1]] >= p:
            dq.pop()
        dq.append(j)
    return best if best < float('inf') else -1
print(shortest([2, -1, 2, -3, 4, 1], 5))
What is printed?
  1. A. 3
  2. B. 4
  3. C. 6
  4. D. 2

Correct answer: D. 2

Prefix sums: 0, 2, 1, 3, 0, 4, 5. The deque keeps increasing prefix values; when P[j] − P[front] ≥ 5 the front can be closed for good. [4, 1] (sum 5, length 2) is the answer; a plain two-pointer window fails because negatives make sums non-monotonic.

More Coding Interview Problems questions

Exams that ask this topic