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?- A. 3
- B. 4
- C. 6
- 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
- Problem: Longest subarray whose max − min ≤ limit, using two monotonic deques. python from collections import deque def longest(a, lim)…
- Problem: Count subarrays whose maximum lies in [L, R] in one pass. python def count(a, L, R): lastbad = lastok = -1; res = 0 for i, x in…
- Problem: Shortest path (in steps) from the top-left to the bottom-right cell of a grid where 1 is a wall, if you may remove at most k…
- Problem: A lock has 4 wheels of digits 0–9; one move turns one wheel by ±1 (wrapping 9↔0). Starting at '0000', find the fewest moves to…
- Problem: Water level t floods every cell of height ≤ t. Find the smallest t at which you can swim from the top-left to the bottom-right…
- Problem: Connect all points with minimum total Manhattan-distance wiring (dense-graph Prim in O(n²)). python def mst(p): n = len(p); dist…