Shortest Subarray with Sum at Least K

Hard

Topics
ArrayPrefix SumSliding WindowDeque

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

10
Input:  nums = [1], target = 1
Output: 1

Example 2

1021
Input:  nums = [1,2], target = 4
Output: -1

Example 3

20-1122
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

  1. Build the prefix sum array of length n+1.
  2. Sweep i from 0 to n.
  3. While the front satisfies the target, record i - front and pop it.
  4. While the back has a prefix sum at least pre[i], pop it.
  5. 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 has n+1 entries 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 -1
SensAI
Beta
Tap the mic to stop voice mode