Skip to content
DSA Patterns
Menu
Language
Sliding WindowLC #2093 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Minimum Size Subarray Sum

Problem (restated)

Given a positive integer array nums and a positive integer target, return the minimal length of a contiguous subarray whose sum is ≥ target. Return 0 if no such subarray exists.

Intuition

Because all values are positive, expanding the right end only increases the sum and shrinking the left only decreases it. classic variable window.

Approaches

Sliding window

Unverified
Time O(n)Space O(1)

Idea. Grow right while sum < target. When sum ≥ target, shrink left as far as possible and track min length.

Walkthrough. nums=[2,3,1,2,4,3], target=7. Window grows to [2,3,1,2] sum=8 → length 4. Shrink to [3,1,2] then [1,2,4]… eventually [4,3] length 2.

Trade-offs. Optimal linear scan. Binary search on prefix sums is O(n log n) and only needed if negatives appear (they do not here).

Solution
export function minSubArrayLen(target: number, nums: number[]): number {
  let left = 0, sum = 0, 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++]!;
    }
  }
  return best === Infinity ? 0 : best;
}
export function minSubArrayLen(target: number, nums: number[]): number {
  let left = 0, sum = 0, 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++]!;
    }
  }
  return best === Infinity ? 0 : best;
}

Template connection

Min window on a positive array. The right edge adds nums[right]. While the sum is at least target, record the length and drop nums[left]. No window that reaches the target answers 0.

Reflection

  • Every value is positive, so extending the right end only raises the sum. What makes the window the right tool?
  • Once sum >= target, if you do not shrink the left as far as it will go, why does the answer stay too large?
  • A negative breaks this scan. What do you switch to? Prefix sums plus binary search.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Shortest subarray with sum ≥ 7. Expand R to grow the sum, shrink L while valid.

2
0
3
1
1
2
2
3
4
4
3
5
Statetarget=7sum=0best=∞

target = 7

Key:CurrentActive rangeMatchSettledEliminated