Skip to content
ΣDSA Patterns
Menu
Language

Sliding Window

Guide 3 of 6 · Path 3 of 6

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 9
a
b
c
a
b
b

best = 0

Start with an empty window. Invariant: all characters unique.

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

Tested only
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;
}

Reflection