Minimum Size Subarray Sum

Shortest contiguous subarray with sum ≥ target via expanding/contracting window over positive integers.

Medium
Time O(n) Space O(1)
LeetCode
3 min read
sliding-window array

Problem#

Given an array of positive integers nums and a target, return the minimal length of a contiguous subarray whose sum is at least target. Return 0 if none.

Examples#

  • target = 7, nums = [2,3,1,2,4,3]2 ([4,3])
  • target = 11, nums = [1,1,1,1,1,1,1,1]0

Constraints#

  • All elements positive.

Approach#

Expand right to grow the sum. Whenever sum ≥ target, shrink left while still valid, recording the shortest.

Solution#

Minimum Size Subarray Sum
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int left = 0, sum = 0, best = INT_MAX;
for (int right = 0; right < (int)nums.size(); ++right) {
sum += nums[right];
while (sum >= target) {
best = min(best, right - left + 1);
sum -= nums[left++];
}
}
return best == INT_MAX ? 0 : best;
}
};

Editorial#

Positivity matters: with negatives, a window’s sum is non-monotonic in length, so shrinking left wouldn’t preserve the search invariant. For arrays with negatives, prefix-sum + sorted structures or deque give an O(n log n) / O(n) alternative.

Complexity#

  • Time: O(n) (each pointer advances ≤ n times).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.