LeetCode #209 Medium

Minimum Size Subarray Sum

Minimum Size Subarray Sum is LeetCode 209 (Medium). Given an array of positive integers nums and a number target, return the length of the shortest contiguous subarray whose sum is at least target. If no subarray reaches target, return 0.

  • With up to 10⁵ elements, summing every subarray (O(n²)) is too slow.
  • The problem adds a follow-up: after the O(n) solution, write one that runs in O(n log n).
Constraints
  • 1 <= target <= 10⁹
  • 1 <= nums.length <= 10⁵
  • 1 <= nums[i] <= 10⁴
arraysliding-windowtwo-pointersprefix-sum
Open on LeetCode ↗
02

Intuition

Because every number is positive, a window's sum only goes up when it grows and only goes down when it shrinks. That makes a window you can slide:

  • Grow the right edge one element at a time.
  • Shrink from the left while the sum is still at least target, recording the length before each removal. Every window you shrink from is valid, and the last one before the sum drops is the shortest valid window ending at this right edge.

A start that was dropped never needs to come back: for a later right edge, the window from that start is longer than one already recorded. So each element enters once and leaves once, which gives O(n).

How to spot this pattern

"Shortest (or longest) subarray whose sum meets a bound", with only non-negative numbers, is a variable-size sliding window. If negatives are allowed the window breaks, and it becomes Shortest Subarray with Sum at Least K (problem 862), which needs a monotonic deque.

03

Approach

Try it first

Before reading on, decide what should happen to a window whose sum already reaches target when you look for something shorter. Then check that the left edge never needs to move back. Aim for O(n) time and O(1) space.

1

Start with an empty window

Set left = 0, total = 0 and best = n + 1. Using n + 1 as "nothing found" works because no real subarray is longer than n.

2

Add the next element on the right

For each right, add nums[right] to total. The new element always joins, since every window considered from now on ends at right.

3

Record and shrink while the sum is enough

While total >= target, update best with right - left + 1, then subtract nums[left] and move left forward. The length is recorded first because the removal may push the sum below target.

4

Return 0 if nothing was found

If best is still n + 1, even the whole array falls short of target, so return 0. Otherwise return best.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def minSubArrayLen(self, target: int, nums: List[int]) -> int:
▶3 n = len(nums)
▶4 left = total = 0
▶5 best = n + 1
▶6 for right in range(n):
▶7 total += nums[right]
▶8 while total >= target:
▶9 best = min(best, right - left + 1)
▶10 total -= nums[left]
▶11 left += 1
▶12 return best if best <= n else 0
203112234435sum0<7targetbestnoneempty window, nothing found yet
left0
total0
bestn + 1
The window starts empty with sum 0. Best starts one longer than the array, a length no real window can have, so it can mean "nothing found".
203112234435RLsum2<7targetbestnoneadd 2 → sum 2, still below 7
right0
total2
Adding 2 gives a sum of 2, short of 7. No window ending here is long enough yet, so keep growing.
203112234435RLsum5<7targetbestnoneadd 3 → sum 5, still below 7
right1
total5
Adding 3 gives a sum of 5, short of 7. No window ending here is long enough yet, so keep growing.
203112234435RLsum6<7targetbestnoneadd 1 → sum 6, still below 7
right2
total6
Adding 1 gives a sum of 6, short of 7. No window ending here is long enough yet, so keep growing.
203112234435RLsum8≥7targetbestnoneadd 2 → sum 8, reaches 7
right3
total8
Adding 2 brings the window sum to 8, which reaches the target of 7. Now the window can try to get shorter from the left.
203112234435RLsum8≥7targetbest4window of 4 has sum 8 → new best 4
length4
best4
The window from 0 to 3 sums to 8 ≥ 7, so its length 4 is recorded as the new best. It is recorded before shrinking, because the next removal might drop the sum below the target.
203112234435RLsum6<7targetbest4drop 2 from the left → sum 6, below 7
left1
total6
Removing 2 leaves 6, below 7, so the shrinking stops. Every start before 1 is gone for good: with a later right edge those windows would only be longer.
203112234435RLsum10≥7targetbest4add 4 → sum 10, reaches 7
right4
total10
Adding 4 brings the window sum to 10, which reaches the target of 7. Now the window can try to get shorter from the left.
203112234435RLsum10≥7targetbest4window of 4 has sum 10, best stays 4
length4
best4
The window from 1 to 4 sums to 10 ≥ 7, so its length 4 is checked, but 4 is already shorter. It is recorded before shrinking, because the next removal might drop the sum below the target.
203112234435RLsum7≥7targetbest4drop 3 from the left → sum 7, still enough
left2
total7
Removing 3 leaves 7, still at least 7. A shorter window works, so the loop records it and keeps shrinking.
203112234435RLsum7≥7targetbest3window of 3 has sum 7 → new best 3
length3
best3
The window from 2 to 4 sums to 7 ≥ 7, so its length 3 is recorded as the new best. It is recorded before shrinking, because the next removal might drop the sum below the target.
203112234435RLsum6<7targetbest3drop 1 from the left → sum 6, below 7
left3
total6
Removing 1 leaves 6, below 7, so the shrinking stops. Every start before 3 is gone for good: with a later right edge those windows would only be longer.
203112234435RLsum9≥7targetbest3add 3 → sum 9, reaches 7
right5
total9
Adding 3 brings the window sum to 9, which reaches the target of 7. Now the window can try to get shorter from the left.
203112234435RLsum9≥7targetbest3window of 3 has sum 9, best stays 3
length3
best3
The window from 3 to 5 sums to 9 ≥ 7, so its length 3 is checked, but 3 is already shorter. It is recorded before shrinking, because the next removal might drop the sum below the target.
203112234435RLsum7≥7targetbest3drop 2 from the left → sum 7, still enough
left4
total7
Removing 2 leaves 7, still at least 7. A shorter window works, so the loop records it and keeps shrinking.
203112234435RLsum7≥7targetbest2window of 2 has sum 7 → new best 2
length2
best2
The window from 4 to 5 sums to 7 ≥ 7, so its length 2 is recorded as the new best. It is recorded before shrinking, because the next removal might drop the sum below the target.
203112234435RLsum3<7targetbest2drop 4 from the left → sum 3, below 7
left5
total3
Removing 4 leaves 3, below 7, so the shrinking stops. Every start before 5 is gone for good: with a later right edge those windows would only be longer.
203112234435sum3<7targetbest2answer: 2
return2
Every right edge was tried, and for each one the shortest valid window ending there was measured. The shortest of all has 2 elements.
05

Prefix sums and binary search

prefix[j] is the sum of the first j numbers, and it only increases because every number is positive. The subarray from i to j - 1 reaches target when prefix[j] >= prefix[i] + target, so for each start i a binary search finds the first such j.

▶1class Solution:
▶2 def minSubArrayLen(self, target: int, nums: List[int]) -> int:
▶3 n = len(nums)
▶4 prefix = [0] * (n + 1)
▶5 for i, x in enumerate(nums):
▶6 prefix[i + 1] = prefix[i] + x
▶7 best = n + 1
▶8 for i in range(n):
▶9 j = bisect_left(prefix, prefix[i] + target)
▶10 if j <= n:
▶11 best = min(best, j - i)
▶12 return best if best <= n else 0
06

Common pitfalls

Shrinking with if instead of while

✗ Wrong
if total >= target:
    best = min(best, right - left + 1)
    total -= nums[left]; left += 1
✓ Right
while total >= target:
    best = min(best, right - left + 1)
    total -= nums[left]; left += 1

One big element can make several left elements unnecessary at once. For nums = [1, 1, 1, 1, 1, 8], target = 8, the answer is 1 (just the 8), but with if the window drops only one element per step. The 8 arrives last, so the code records the window of 6 and returns 6.

Returning n + 1 when nothing reaches target

✗ Wrong
return best
✓ Right
return best if best <= n else 0

The placeholder leaks out as an answer. For nums = [1, 1, 1, 1], target = 11, the code returns 5, a length longer than the array, instead of 0.

07

Edge cases

One element already reaches target

The window shrinks down to that single element, so best becomes 1, the smallest possible answer.

The whole array sums to exactly target

The window only becomes valid at the last element, and removing anything drops below target, so the answer is n.

08

Complexity

Time
O(n)
Space
O(1)
right passes each element once, and left only moves forward, so it also passes each element at most once. Only a few integers are stored. The sum fits in 32 bits: at most 10⁵ × 10⁴ = 10⁹.
09

Minimum Size Subarray Sum FAQ

Why does the sliding window fail with negative numbers?

Shrinking assumes that removing an element lowers the sum. A negative number breaks that. For [84, -37, 32, 40, 95] with target = 167, the sum first reaches 167 with all five numbers; dropping the 84 falls to 130, so the window stops there and returns 5. Yet [32, 40, 95] sums to 167 with length 3. Shortest Subarray with Sum at Least K handles negatives with a monotonic deque of prefix sums.

Is this the same as Smallest Subarray With Sum Greater Than X?

Nearly. That version needs a sum strictly greater than x, so the loop condition becomes total > x. Everything else, including the window and the proof, stays the same.

How do I return the subarray itself instead of its length?

Save left and right whenever best improves. The saved pair marks the shortest window; if several share the length, this keeps the first one found.