Minimum Size Subarray Sum

Medium20 min
Given a positive integer target and an array of positive integers nums, return the length of the shortest non-empty contiguous subarray whose sum is at least target. Return 0 if no such subarray exists.

For target = 7 and nums = [2, 3, 1, 2, 4, 3], the shortest qualifying subarray is [4, 3], so the answer is 2.

Move right across the array and add each new value to window_sum. When the sum reaches target, the current window is valid, but values at its left edge may not be necessary. Record its length, then remove nums[left] and move left forward. Continue shrinking while the remaining sum is still at least target.

Because every value is positive, adding a value can only increase the window sum, while removing a value can only decrease it. Once removing nums[left] drops the sum below target, removing more values cannot make the window valid again. The algorithm must move right forward and add another value.

For a fixed right, moving left forward makes the window shorter. The loop records each window while its sum is still at least target, so the last valid length recorded is the shortest qualifying window ending at right. Comparing those candidates gives the shortest qualifying subarray overall.

Shrink every window whose sum reaches 7

1 / 13
window_sum
2
best_length
not found
Step 1 of 13.
Start with left and right at index 0. The sum is 2, below the target, so move right.
  • current window
  • value removed
Why does the shrinking condition use a while loop instead of one if?
1class Solution:
2 def minSubArrayLen(self, target: int, nums: List[int]) -> int:
3 res = float("inf")
4 left = 0
5 window_sum = 0
6
7 for right, value in enumerate(nums):
8 window_sum += value
9 while window_sum >= target:
10 res = min(res, right - left + 1)
11 window_sum -= nums[left]
12 left += 1
13
14 return 0 if res == float("inf") else res

If no window ever reaches the target, res remains infinity. The final return converts that sentinel to 0, as required by the problem.

Time: O(n)Space: O(1)

Each value enters the window once and leaves it at most once, so the two pointers make O(n) total moves. The algorithm stores two boundaries, the current sum, and the best length.

You reached the end of the free preview

Continue into counting windows, prefix sums, hash maps, trees, graphs, backtracking, and dynamic programming with AlgoDrill Pro.