The Shortest Subarray with Sum at Least K interview question gives you an integer array that may contain negative numbers and an integer K. Find the length of the shortest contiguous subarray whose sum is at least K. If no such subarray exists, return -1. The presence of negative numbers makes this much harder than the positive-only sliding window version and requires a monotonic deque with prefix sums.
Goldman Sachs, Microsoft, Meta, Amazon, Google, and Bloomberg ask this HARD problem because it is the canonical application of a monotonic deque on prefix sums. With only positive numbers, a simple two-pointer works. But negative numbers break the monotone property of the sliding window sum — necessitating the deque-based approach. It tests deep understanding of when and why deque-based optimization is needed over simpler techniques.
The pattern is prefix sum + monotonic deque. Compute prefix sums P[i] where P[0]=0 and P[i] = P[i-1] + nums[i-1]. Finding a subarray nums[i..j] with sum ≥ K is equivalent to finding P[j+1] - P[i] >= K, i.e., P[j+1] >= P[i] + K. Use a monotonic deque of indices with increasing prefix sums: for each new index j, pop from the front while P[j] - P[deque.front()] >= K (found a valid subarray — track minimum length). Then pop from the back while P[j] <= P[deque.back()] (maintain monotone increasing order). Push j to the back.
nums = [2, -1, 2], K = 3.
Prefix sums: P = [0, 2, 1, 3].
Deque processing:
Minimum length: 3 (entire array).
n+1 — the deque operates on prefix sums including P[0]=0.P[j] < P[deque.back()] incorrectly — pop when <= to maintain strictly increasing deque.For the Shortest Subarray with Sum at Least K coding problem, the monotonic queue prefix sum array interview pattern is the O(n) solution. The deque maintains indices with increasing P values — when P[j] - P[front] >= K, the front index gives the farthest valid left boundary, and popping the front reveals the next candidate. Goldman Sachs and Bloomberg interviewers test whether you know why the simple sliding window fails here. Practice the P[j] - P[i] >= K reformulation as the key that unlocks the monotonic deque approach for this problem class.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Maximum Number of Robots Within Budget | Hard | Solve | |
| Max Value of Equation | Hard | Solve | |
| Sliding Window Maximum | Hard | Solve | |
| Maximize the Minimum Powered City | Hard | Solve | |
| Constrained Subsequence Sum | Hard | Solve |