Minimum Size Subarray Sum

Medium

Topics
ArraySliding WindowTwo Pointers

Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray whose sum is ≥ target. If there is none, return 0.

Example 1

203112234435length 2
The braced run is the shortest contiguous block summing to at least 7 — length 2. Because all values are positive the window is monotonic: grow right to reach the target, then pull the left edge in while the target still holds.
Cells are the array values; the small numbers underneath are indices.
Input:  target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has sum 7 and length 2.

Example 2

1011121314
No block reaches 11, so the answer is 0.
Input:  target = 11, nums = [1,1,1,1,1]
Output: 0

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^4
  • 1 <= target <= 10^9
Editorial — intuition, approach, complexity and pitfalls

Intuition

All numbers are positive, so growing the window only increases the sum and shrinking only decreases it — a sliding window works.

Expand the right edge until the sum reaches the target, then shrink from the left as far as possible while still ≥ target, recording the smallest width.

Approach

  1. Move the right end, adding to the running sum.
  2. While the sum ≥ target, record the window length and remove the left element (shrink).
  3. Track the minimum length; 0 if the target is never reached.

Walkthrough

target=7, nums=[2,3,1,2,4,3]
window grows to [2,3,1,2] sum 8, shrink -> [3,1,2] len 3
... eventually [4,3] sum 7 len 2 -> answer 2

Complexity

  • Time — O(n): each element enters and leaves the window at most once.
  • Space — O(1): a few scalars.

Common Pitfalls

  • This relies on all-positive values; with negatives you would need a different (prefix-sum + deque) approach.

Full Solution — all languages

class Solution:
    def minSubArrayLen(self, nums, target):
        lo = s = 0
        res = float('inf')
        for hi in range(len(nums)):
            s += nums[hi]
            while s >= target:
                res = min(res, hi - lo + 1)
                s -= nums[lo]
                lo += 1
        return res if res != float('inf') else 0
Asked at DoorDash
SensAI
Beta
Tap the mic to stop voice mode