Shortest Subarray with Sum at Least K
Hard
Topics
Given an integer array nums and an integer target, return the length of the shortest non-empty contiguous subarray whose sum is at least target. If there is no such subarray, return -1.
Example 1
Input: nums = [1], target = 1 Output: 1
Example 2
Input: nums = [1,2], target = 4 Output: -1
Example 3
Input: nums = [2,-1,2], target = 3 Output: 3
Constraints
- 1 <= nums.length <= 10^5
- -10^5 <= nums[i] <= 10^5
- 1 <= target <= 10^9
Editorial — intuition, approach, complexity and pitfalls
Intuition
Negative values are allowed, which kills the sliding window used for the all-positive version: extending the window can now decrease the sum, so there is no monotone invariant to shrink against. Prefix sums plus a monotonic deque recover the linear time.
With pre[i] the sum of the first i elements, a subarray [j, i) qualifies when pre[i] - pre[j] >= target. Scanning i rightward, keep candidate j values in a deque with increasing prefix sums.
Two discard rules make it work. From the front: if pre[i] - pre[front] already meets the target, record the length and pop — any later i gives a longer subarray with the same start, so this j is finished. From the back: if pre[last] >= pre[i], drop it — i is both a later start and a smaller prefix, so it dominates.
Approach
- Build the prefix sum array of length
n+1. - Sweep
ifrom 0 ton. - While the front satisfies the target, record
i - frontand pop it. - While the back has a prefix sum at least
pre[i], pop it. - Push
i.
Dry Run
nums = [2,-1,2,1] target = 3
prefix sums [0, 2, 1, 3, 4]
i pre[i] front pops (window found) deque after note
0 0 -- [0]
1 2 -- [0,1]
2 1 -- [0,2] dropped 1: pre[1]=2 >= pre[2]=1
3 3 j=0, length 3 [2,3]
4 4 j=2, length 2 [3,4]
answer 2 the subarray [2,1] at indices 2..3
index 1 is dropped from the back because index 2 starts later AND has a smaller
prefix sum -- it dominates index 1 for every future i.Complexity
- Time — O(n): each index is pushed once and popped once across the whole sweep, so both inner loops are amortised constant.
- Space — O(n) for the prefix array and the deque.
Common Pitfalls
- Using a two-pointer sliding window. With negatives there is no monotonicity to shrink against, and the window version silently answers a different question — this is the single most important thing to say about this problem.
- Popping from the front without recording the length first. The front is the longest-standing candidate and its length is the one being measured.
- Using
>instead of>=in the back-discard. Equal prefix sums mean the later index is strictly better, so it should still evict. - Starting the sweep at
i = 1. The prefix array hasn+1entries and index 0 is a legitimate start position, which the dry run uses. - Returning 0 rather than -1 when nothing qualifies. The sentinel has to be distinguishable from a real answer.
- Storing prefix sums in the deque instead of indices, which loses the start position needed to compute a length.
Full Solution — all languages
class Solution:
def shortestSubarray(self, nums, target):
from collections import deque
n = len(nums)
pre = [0] * (n + 1)
for i in range(n):
pre[i + 1] = pre[i] + nums[i]
dq = deque()
best = n + 1
for i in range(n + 1):
while dq and pre[i] - pre[dq[0]] >= target:
best = min(best, i - dq.popleft())
while dq and pre[dq[-1]] >= pre[i]:
dq.pop()
dq.append(i)
return best if best <= n else -1import java.util.*;
class Solution {
public int shortestSubarray(int[] nums, int target) {
int n = nums.length;
long[] pre = new long[n + 1];
for (int i = 0; i < n; i++) pre[i + 1] = pre[i] + nums[i];
Deque<Integer> dq = new ArrayDeque<>();
int best = n + 1;
for (int i = 0; i <= n; i++) {
while (!dq.isEmpty() && pre[i] - pre[dq.peekFirst()] >= target) {
best = Math.min(best, i - dq.pollFirst());
}
while (!dq.isEmpty() && pre[dq.peekLast()] >= pre[i]) dq.pollLast();
dq.addLast(i);
}
return best <= n ? best : -1;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int shortestSubarray(vector<int>& nums, int target) {
int n = nums.size();
vector<long long> pre(n + 1, 0);
for (int i = 0; i < n; i++) pre[i + 1] = pre[i] + nums[i];
deque<int> dq;
int best = n + 1;
for (int i = 0; i <= n; i++) {
while (!dq.empty() && pre[i] - pre[dq.front()] >= target) {
best = min(best, i - dq.front());
dq.pop_front();
}
while (!dq.empty() && pre[dq.back()] >= pre[i]) dq.pop_back();
dq.push_back(i);
}
return best <= n ? best : -1;
}
};/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/ var shortestSubarray = function(nums, target) {
const n = nums.length;
const pre = new Array(n + 1).fill(0);
for (let i = 0; i < n; i++) pre[i + 1] = pre[i] + nums[i];
const dq = [];
let head = 0, best = n + 1;
for (let i = 0; i <= n; i++) {
while (head < dq.length && pre[i] - pre[dq[head]] >= target) {
best = Math.min(best, i - dq[head]);
head++;
}
while (dq.length > head && pre[dq[dq.length - 1]] >= pre[i]) dq.pop();
dq.push(i);
}
return best <= n ? best : -1;
};