Shortest Subarray with Sum at Least K (LeetCode 862): Solution and Explanation
Negative numbers break the plain shrinking window, so turn every subarray sum into a difference of two prefix sums. A deque of left ends with increasing prefix values answers each right end in amortized O(1).
Intuition
With only positive numbers you could grow a window until the sum reaches k and then shrink it. A negative value ruins that: shrinking can raise the sum and growing can lower it, so the window has no monotone behaviour.
Prefix sums fix the view. The sum of nums[i..j-1] is prefix[j] - prefix[i], so for every right end j we want the closest left end i with prefix[i] <= prefix[j] - k.
Two observations prune the left ends. If an earlier index has a prefix at least as large as a later one, the later one is both closer and lower, so the earlier one is useless. And once a left end has produced a valid window, later right ends can only make that window longer, so it can be dropped. The survivors form an increasing deque.
Approach: Prefix sums with a monotonic deque
- Build
prefixof lengthn + 1withprefix[0] = 0, using 64-bit integers. - Set
best = n + 1and start with an empty deque of indices. - For each
jfrom 0 ton, pop from the front whileprefix[j] - prefix[front] >= k, updatingbestwithj - front. - Then pop from the back while
prefix[back] >= prefix[j]. - Append
jto the back. - Return
bestif it is at mostn, otherwise -1.
Step-by-step example
nums = [1], k = 1
- prefix = [0, 1].
- j = 0: the deque is empty, so nothing to pop. Append 0. Deque = [0].
- j = 1: prefix[1] - prefix[0] = 1 >= 1, so the window nums[0..0] has length 1. best = 1, pop 0.
- The deque is empty, append 1.
- best = 1 <= n, so the answer is 1.
Code: Python, Java, C++
1class Solution:
2 def shortestSubarray(self, nums: List[int], k: int) -> int:
3 n = len(nums)
4 prefix = [0] * (n + 1)
5 for i, x in enumerate(nums):
6 prefix[i + 1] = prefix[i] + x
7 best = n + 1
8 dq = deque()
9 for j in range(n + 1):
10 while dq and prefix[j] - prefix[dq[0]] >= k:
11 best = min(best, j - dq.popleft())
12 while dq and prefix[dq[-1]] >= prefix[j]:
13 dq.pop()
14 dq.append(j)
15 return best if best <= n else -11class Solution {
2 public int shortestSubarray(int[] nums, int k) {
3 int n = nums.length;
4 long[] prefix = new long[n + 1];
5 for (int i = 0; i < n; i++) {
6 prefix[i + 1] = prefix[i] + nums[i];
7 }
8 int best = n + 1;
9 Deque<Integer> dq = new ArrayDeque<>();
10 for (int j = 0; j <= n; j++) {
11 while (!dq.isEmpty() && prefix[j] - prefix[dq.peekFirst()] >= k) {
12 best = Math.min(best, j - dq.pollFirst());
13 }
14 while (!dq.isEmpty() && prefix[dq.peekLast()] >= prefix[j]) {
15 dq.pollLast();
16 }
17 dq.offerLast(j);
18 }
19 return best <= n ? best : -1;
20 }
21}1class Solution {
2public:
3 int shortestSubarray(vector<int>& nums, int k) {
4 int n = nums.size();
5 vector<long long> prefix(n + 1, 0);
6 for (int i = 0; i < n; i++) {
7 prefix[i + 1] = prefix[i] + nums[i];
8 }
9 int best = n + 1;
10 deque<int> dq;
11 for (int j = 0; j <= n; j++) {
12 while (!dq.empty() && prefix[j] - prefix[dq.front()] >= k) {
13 best = min(best, j - dq.front());
14 dq.pop_front();
15 }
16 while (!dq.empty() && prefix[dq.back()] >= prefix[j]) {
17 dq.pop_back();
18 }
19 dq.push_back(j);
20 }
21 return best <= n ? best : -1;
22 }
23};Time and space complexity
O(n)
Each prefix index is appended once and popped at most once, from either end.
O(n)
The prefix array and the deque each hold up to n + 1 entries.
Other approaches
Check every pair (time O(n^2), space O(1))
Try every start and extend the end while tracking the sum. Correct but quadratic, far too slow for 10^5 elements.
Prefix sums with a min-heap (time O(n log n), space O(n))
Push (prefix[i], i) into a min-heap and, for each j, pop entries whose prefix is small enough. Simpler to reason about but pays a log factor.
Common mistakes
- Using the classic shrink-while-valid window. It only works when every value is positive and gives wrong answers here.
- Storing prefix sums in 32-bit integers. They can reach 10^10 in magnitude, and
prefix[j] - prefix[i]overflows. - Popping the back with
>instead of>=. Equal prefixes still make the earlier index useless, and keeping it does not break correctness but wastes work. - Forgetting index 0 for the empty prefix, which misses windows that start at the first element.
Frequently asked questions
Why is it safe to pop the front after recording a window?
Any later right end j' > j paired with the same left end gives a longer window, so that left end can never improve the answer again.
Why pop the back when its prefix is at least prefix[j]?
Index j is later and has a lower or equal prefix. For any future right end, j makes a window that is shorter and has a sum at least as large, so the older index is dominated.
How is this different from Minimum Size Subarray Sum?
That problem has only positive numbers, so a two-pointer window is enough. Negative values here require prefix sums and the deque.
What is the time and space complexity?
O(n) time, since each index enters and leaves the deque once, and O(n) space for the prefix array and the deque.