#209
Medium
Sliding Window

Minimum Size Subarray Sum

Find the shortest subarray whose sum is at least target.

Find the minimum length of a contiguous subarray whose sum is at least target. Because all numbers are positive, once the window reaches target you should shrink immediately.

ArraySliding Window

Pattern fit

All numbers are positive, so once the current sum reaches the target, shrinking the left side is the only way to search for a shorter valid window.

Key observation

Positivity makes the window sum monotonic with pointer movement, which is exactly why sliding window beats prefix-sum search here.

Target complexity

O(n) / O(1)

How to break down the solution cleanly

1

Maintain a running sum for the current window.

2

Expand right until the sum reaches or exceeds target.

3

While the window is still valid, update the answer and shrink from the left.

4

The positivity guarantee is what makes this shrinking logic correct.

Walk through one example

1

Example: target = 7, nums = [2, 3, 1, 2, 4, 3].

2

After expanding to [2, 3, 1, 2], sum = 8, so answer can be 4.

3

Shrink left to get [3, 1, 2], sum = 6, which becomes invalid.

4

Continue until [4, 3] appears, and answer improves to 2.

Reference implementation

Python
def minSubArrayLen(target: int, nums: list[int]) -> int:
    left = 0
    window_sum = 0
    best = float("inf")

    for right, value in enumerate(nums):
        window_sum += value

        while window_sum >= target:
            best = min(best, right - left + 1)
            window_sum -= nums[left]
            left += 1

    return 0 if best == float("inf") else best

Common pitfalls

warning

Using sliding window on arrays that may contain negatives.

warning

Updating the answer before shrinking all still-valid prefixes.

Common follow-ups

Why would negatives break the same window logic?

How would a prefix-sum + binary-search solution compare?

Continue with related problems

Build repeatable depth inside the Sliding Window cluster before moving on.

view_weekBack to the pattern page
LeetCode 209. Minimum Size Subarray Sum Guide | Interview AiBox