Engineered
Algorithm Patterns

Minimum Size Subarray Sum

Use a shrinking sliding window to find the shortest qualifying subarray.

Try It Yourself

Use the editor below to find the shortest contiguous window whose sum reaches the target. The positive input values allow the window to shrink safely whenever its sum is large enough.

Submit your implementation when it passes the examples. Return zero if no window reaches the target.

Minimum Size Subarray Sum

mediumSliding Window · Arrays30 minLC 209
Problem

Given an array of positive integers nums and a positive integer target, return the smallest length of a contiguous subarray whose sum is at least target.

Return 0 when no qualifying subarray exists.

Example 1:

Input: target = 7, nums = [2, 3, 1, 2, 4, 3]
Output: 2
Explanation: [4, 3] reaches the target.

Example 2:

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

Constraints

  • 1 ≤ nums.length ≤ 100,000
  • All values and target are positive integers.
0 attempts

Solution

Expand the right edge and add each value to the running sum. Whenever the sum reaches the target, record the current length and repeatedly remove values from the left to search for a shorter valid window.

If no valid length was recorded, return zero.

function minSubArrayLen(target, nums) {
  let left = 0;
  let sum = 0;
  let shortest = Infinity;

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

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

  return shortest === Infinity ? 0 : shortest;
}

Big O notation

MeasureComplexityExplanation
TimeO(n)Each value is added once and removed from the window at most once.
Auxiliary spaceO(1)The window is represented by indices and a running sum.

How is this lesson?