medium

Minimum Size Subarray Sum

Find the shortest contiguous subarray whose sum is at least a target value.

1. Define the problem

Minimum Size Subarray Sum

Given positive integers nums and a target, return the length of the shortest contiguous subarray whose sum is at least target , or 0 if none exists. Grow the sum on the right, then shrink from the left while the sum still meets the target to minimize length.

Constraints

  • 1 ≤ target ≤ 109
  • 1 ≤ nums.length ≤ 105
  • 1 ≤ numsi ≤ 104

Example

Inputtarget = 7, nums = [2, 3, 1, 2, 4, 3]
Output2

Explanation The subarray [4, 3] has sum 7 and is the shortest that qualifies.

2. Visualize the solution

Shrink while sum stays >= target

Shrink while sum stays >= target
Statushit

Window [2,3,1,2] sums to 8 >= 7; length 4 is a candidate.

What happens in this step

window = [0, 3]  sum = 2+3+1+2 = 8

before: sum = 6 (right = 2), best = Infinity
  add nums[3] = 2 → sum = 8

8 >= target 7, so this whole window is a valid candidate — best becomes 4 (its length).
Step 1 of 4

Steps to visualize

  1. Grow right and add each new value into the running window sum.
  2. While the sum is at least target, record the window length as a candidate.
  3. Then drop the leftmost value and advance left to try a shorter window.
  4. Keep the smallest length that still meets the target.
  5. If no window ever qualifies, return 0.
3. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Shrink while sum stays >= target
Statushit

Window [2,3,1,2] sums to 8 >= 7; length 4 is a candidate.

What happens in this step

window = [0, 3]  sum = 2+3+1+2 = 8

before: sum = 6 (right = 2), best = Infinity
  add nums[3] = 2 → sum = 8

8 >= target 7, so this whole window is a valid candidate — best becomes 4 (its length).
Step 1 of 4
4. Solution

Solution

solution.tsTypeScript
function minSubArrayLen(target, nums) {
  let left = 0;
  let sum = 0;
  let best = Infinity;

  for (let right = 0; right < nums.length; right++) {
    sum += nums[right];

    while (sum >= target) {
      best = Math.min(best, right - left + 1);
      sum -= nums[left];
      left++;
    }
  }

  return best === Infinity ? 0 : best;
}
Time
O(n)
Space
O(1)
5. Test cases

Test cases

InputExpectedCovers
target = 7, nums = [2, 3, 1, 2, 4, 3]2Docstring example — [4, 3]
target = 5, nums = [5]1Single element meeting target
target = 15, nums = [1, 2, 3, 4, 5]5Entire array is the answer
target = 100, nums = [1, 2, 3]0No valid window exists
target = 9, nums = [3, 3, 3, 3, 3]3All identical elements
target = 4, nums = [1, 4, 4]1Classic LeetCode example with a single 4
target = 11, nums = [1, 2, 3, 4, 5]3Best is [3, 4, 5] length 3