Tensorum
LeetCode 209 · Variable Window – Shortest / Minimum

Minimum Size Subarray Sum

LeetCode 209 · Medium · solution, intuition & step-by-step walkthrough

Positive numbers ⇒ expand then shrink.

MediumArrayBinary SearchSliding WindowPrefix Sum
15 msruntime · beats 95%
30.6 MBmemory · beats 35%
1approach
4accepted runs · last 7 Mar 2026

This is how I solved Minimum Size Subarray Sum (LeetCode 209), a medium problem from the Variable Window – Shortest / Minimum pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

All numbers are positive, so extending a window only increases its sum and shrinking only decreases it. Expand right until the sum reaches the target, then shrink from the left while it still does, recording the shortest length.

Approach

  1. 1

    Add nums[r] to the sum.

  2. 2

    While sum ≥ target: record r − l + 1, subtract nums[l], l++.

  3. 3

    Return 0 if nothing qualified.

How I solved it

Sliding windowPythonO(n) time · O(1) space
class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        l=0
        r=0
        sum=0
        min_length = float("inf")
        while r<len(nums):
            sum+=nums[r]
            while sum>=target:
                min_length = min(min_length,r-l+1)
                sum-=nums[l]
                l+=1
            r+=1
        return 0 if min_length==float("inf") else min_length
Loading the step-through…

Minimum Size Subarray Sum — FAQ

What is the intuition behind Minimum Size Subarray Sum?

All numbers are positive, so extending a window only increases its sum and shrinking only decreases it. Expand right until the sum reaches the target, then shrink from the left while it still does, recording the shortest length.

How do you solve Minimum Size Subarray Sum (LeetCode 209)?

1. Add nums[r] to the sum. 2. While sum ≥ target: record r − l + 1, subtract nums[l], l++. 3. Return 0 if nothing qualified.

What is the time and space complexity of Minimum Size Subarray Sum?

Time: O(n). Space: O(1). (Accepted approach: Sliding window.)

What are common mistakes in Minimum Size Subarray Sum?

Sliding window relies on positivity — with negatives use prefix sums.