Shortest Subarray with Sum at Least K (LeetCode 862): Solution and Explanation

Hard
Array
Binary search
Queue
Sliding window
Heap
Prefix sum
Monotonic queue

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

  1. Build prefix of length n + 1 with prefix[0] = 0, using 64-bit integers.
  2. Set best = n + 1 and start with an empty deque of indices.
  3. For each j from 0 to n, pop from the front while prefix[j] - prefix[front] >= k, updating best with j - front.
  4. Then pop from the back while prefix[back] >= prefix[j].
  5. Append j to the back.
  6. Return best if it is at most n, otherwise -1.

Step-by-step example

nums = [1], k = 1
  1. prefix = [0, 1].
  2. j = 0: the deque is empty, so nothing to pop. Append 0. Deque = [0].
  3. j = 1: prefix[1] - prefix[0] = 1 >= 1, so the window nums[0..0] has length 1. best = 1, pop 0.
  4. The deque is empty, append 1.
  5. 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 -1
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each prefix index is appended once and popped at most once, from either end.

Space

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.