Skip to content
Problem 209 · LeetCode 209(opens in a new tab)

Minimum Size Subarray Sum

MediumArrays

You get a list of positive whole numbers, nums, and a positive number target. Look for a run of neighbouring numbers in the list (a subarray) whose sum is at least target.

Return the length of the shortest such run. If even the whole list adds up to less than target, return 0.

Example 1

Input:  target = 8, nums = [2, 1, 5, 3, 4]
Output: 2
Why:    5 + 3 = 8, and no single number reaches 8
2 more examples and the constraints

Example 2

Input:  target = 6, nums = [1, 6, 2]
Output: 1
Why:    the 6 on its own is enough

Example 3

Input:  target = 20, nums = [3, 3, 3, 3]
Output: 0
Why:    the whole list only adds up to 12

Constraints

  • 1 ≤ length of nums ≤ 100,000
  • 1 ≤ each number ≤ 10,000
  • 1 ≤ target ≤ 1,000,000,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try every startO(n²)
  2. Prefix sums + binary searchO(n log n)
  3. Sliding windowO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 numbersVerdict
Try every startO(n²)
Too slow for big targets
Prefix sums + binary searchO(n log n)
Passes; the follow-up answer
Sliding windowO(n)
Best; two pointers, no memory

n = how many numbers are in the list.

Edge cases to test

  • No window is enough. [3, 3, 3, 3] with target 20 never reaches it: return 0, not n + 1.
  • One number is enough. [1, 6, 2] with target 6 gives 1. The loop must record before it shrinks.
  • The whole list is needed. [1, 2, 3, 4] with target 10 gives 4.
  • At least, not exactly. [3, 3, 3, 1] with target 7 gives 3, even though no run sums to exactly 7.

Common mistakes

  • Using if instead of while for the shrink, so the window drops only one number per step and misses shorter answers.
  • Returning the sentinel n + 1 (or infinity) when no window works, instead of 0.
  • Checking for a sum of exactly target instead of at least target.

How to talk through it

  1. 1Clarify. Are all numbers positive? Is it at least the target or exactly? What do I return if nothing works?
  2. 2Give the brute force. Try every start and extend until the sum is enough; O(n²) in the worst case.
  3. 3Use positivity. Adding a number only grows the sum and dropping one only shrinks it, so a window can slide.
  4. 4Code the window. Grow on the right, shrink on the left inside a while loop, record before each shrink.
  5. 5Test out loud. Run the no-answer case, a single number that is enough, and a case that needs the whole list.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?