Minimum Size Subarray Sum

Medium Sliding Window AI round

nums is a list of positive whole numbers, and target is a positive whole number.

A subarray is a run of one or more numbers that sit next to each other in nums. Find the shortest subarray whose numbers add up to target or more.

Return the length of that subarray, or 0 if there is none: when even the whole list adds up to less than target.

Example 1

Input: target = 10, nums = [4,1,2,6,3,5]
Output: 3

2 + 6 + 3 = 11 reaches the target with three numbers next to each other. No two neighbours add up to 10 or more (the most is 6 + 3 = 9), so nothing shorter works.

Example 2

Input: target = 20, nums = [3,7,2,5]
Output: 0

All four numbers add up to 17, less than 20, so no subarray reaches the target.

Example 3

Input: target = 12, nums = [5,1,6]
Output: 3

Constraints

  • 1 ≤ nums.length ≤ 2 × 10⁵
  • 1 ≤ nums[i] ≤ 5000
  • 1 ≤ target ≤ 10⁹

Watch the explanation

More Sliding Window

All Sliding Window problems