02. Shortest Subarray with Sum at Least K

Difficulty:HardPattern:Prefix Sum + Monotonic DequeTime:O(n)Space:O(n)

Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k.

How It Works & Algorithmic Design

Solves using Prefix Sum Array + Monotonic Double-Ended Queue (Deque):

  1. Prefix Sum: Build P[i] = P[i-1] + nums[i-1] of length $n + 1$.
  2. Monotonic Deque: Store indices $i$ in deque such that $P[i]$ is strictly increasing.
  3. Loop Index $i$ from $0$ to $n$:
    • Contract Left: While P[i] - P[deque[0]] >= k, update minLen = Math.min(minLen, i - deque.shift()).
    • Maintain Monotonicity: While P[i] <= P[deque[last]], pop back (a smaller prefix sum at a larger index is always a better left boundary choice).
    • Push $i$ onto deque.

Why This Approach Works Best

Handles negative numbers while finding valid sub-arrays in linear $O(n)$ time.

Example Walkthrough

Input

nums = [2,-1,2], k = 3

Target sum 3 with negative values.

Prefix Sums

P = [0, 2, 1, 3]. Subarray [2,-1,2] sum = P[3]-P[0] = 3.

Length 3 subarray.

Output

3

Shortest subarray length.

Answer: Shortest Subarray with Sum at Least K implementation

function shortestSubarray(nums, k) {
  const n = nums.length;
  const P = new Array(n + 1).fill(0);
  for (let i = 0; i < n; i++) P[i + 1] = P[i] + nums[i];
  let minLen = Infinity;
  const deque = [];
  for (let i = 0; i <= n; i++) {
    while (deque.length && P[i] - P[deque[0]] >= k) {
      minLen = Math.min(minLen, i - deque.shift());
    }
    while (deque.length && P[i] <= P[deque[deque.length - 1]]) {
      deque.pop();
    }
    deque.push(i);
  }
  return minLen === Infinity ? -1 : minLen;
}

Maintain monotonically increasing prefix sum indices in a deque to query minimal subarray lengths.

Key Takeaways
  • Works with negative array numbers unlike simple two-pointer sliding windows.

  • Popping larger prefix sums maintains monotonic deque structure.

  • Executes in $O(n)$ time.