Loading problems...
TL;DR: Use a variable-size sliding window approach to expand a window until the sum constraint is met, then shrink it from the left to find the minimal length.
The Minimum Size Subarray Sum problem asks us to find the length of the shortest contiguous subarray within an array of positive integers, nums, such that the sum of the subarray is greater than or equal to a specific target. If no such subarray exists, the function should return 0. This is a classic optimization problem found in coding interviews, often referred to as LeetCode 209.
The naive approach involves checking every possible contiguous subarray to see if its sum meets the target, and then determining which valid subarray has the minimum length.
To achieve this, we would use two nested loops. The outer loop selects the starting index i, and the inner loop selects the ending index j. For every pair (i, j), we calculate the sum of elements between them.
textInitialize min_length to infinity For i from 0 to length(nums) - 1: Initialize current_sum to 0 For j from i to length(nums) - 1: current_sum += nums[j] If current_sum >= target: min_length = min(min_length, j - i + 1) Break (since extending j further only increases length) Return min_length (or 0 if unchanged)
Time Complexity Analysis:
The time complexity is , where is the number of elements in nums. In the worst case, for every starting position, we iterate through the rest of the array.
Why it fails:
The problem constraints state that nums.length can be up to . An solution results in approximately operations, which far exceeds the typical limit of operations per second allowed by online judges. This leads to a Time Limit Exceeded (TLE) error.
The transition from the brute force approach to the optimal solution relies on the property that all numbers in the input array are positive.
Because the numbers are positive, adding an element to the subarray always increases the sum, and removing an element always decreases the sum. This monotonicity allows us to avoid recalculating sums from scratch.
Instead of resetting our starting point for every iteration, we can maintain a "window" defined by two pointers, left and right.
right pointer to include more elements until the window's sum meets the target.sum >= target), the current window is a candidate solution.left as much as possible while keeping the sum target.Visual Description:
Imagine the array as a strip of tape. You unroll the tape to the right (increment right) to gather enough sum. Once you have enough, you roll up the left side of the tape (increment left) to make the strip as short as possible without dropping below the target sum. This caterpillar-like movement ensures we check all potential minimal windows in a single pass.

Let's trace nums = [2, 3, 1, 2, 4, 3], target = 7.
window_start = 0, window_end = 0, sum = 0, min_len = .sum=2). sum < 7.sum=5). sum < 7.sum=6). sum < 7.sum=8). sum >= 7. Condition met.
[2,3,1,2]). Subtract 2 (sum=6). Increment window_start to 1.sum < 7, stop shrinking.sum=10). sum >= 7.
[3,1,2,4]). Subtract 3 (sum=7). Increment window_start to 2.[1,2,4]). Subtract 1 (sum=6). Increment window_start to 3.sum < 7, stop shrinking.sum=9). sum >= 7.
[2,4,3]). Subtract 2 (sum=7). Increment window_start to 4.[4,3]). Subtract 4 (sum=3). Increment window_start to 5.sum < 7, stop shrinking.window_end reaches end of array.The algorithm is correct because it implicitly considers all valid starting positions. For any window_end, the logic finds the largest window_start such that sum(nums[window_start...window_end]) >= target.
Since elements are positive, any subarray ending at window_end starting before our calculated window_start would be valid but longer (suboptimal). Any subarray ending at window_end starting after our calculated window_start would have a sum less than target (invalid). Thus, for every ending position, we find the local optimal length. The global minimum of these local optimums is the correct answer.
cpp#include <vector> #include <algorithm> #include <climits> class Solution { public: int minSubArrayLen(int target, std::vector<int>& nums) { int min_length = INT_MAX; int current_sum = 0; int window_start = 0; for (int window_end = 0; window_end < nums.size(); ++window_end) { current_sum += nums[window_end]; // Shrink the window as small as possible while the sum is valid while (current_sum >= target) { min_length = std::min(min_length, window_end - window_start + 1); current_sum -= nums[window_start]; window_start++; } } return (min_length == INT_MAX) ? 0 : min_length; } };
javaclass Solution { public int minSubArrayLen(int target, int[] nums) { int minLength = Integer.MAX_VALUE; int currentSum = 0; int windowStart = 0; for (int windowEnd = 0; windowEnd < nums.length; windowEnd++) { currentSum += nums[windowEnd]; // Shrink the window as small as possible while the sum is valid while (currentSum >= target) { minLength = Math.min(minLength, windowEnd - windowStart + 1); currentSum -= nums[windowStart]; windowStart++; } } return (minLength == Integer.MAX_VALUE) ? 0 : minLength; } }
pythonclass Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: min_length = float('inf') current_sum = 0 window_start = 0 for window_end in range(len(nums)): current_sum += nums[window_end] # Shrink the window as small as possible while the sum is valid while current_sum >= target: min_length = min(min_length, window_end - window_start + 1) current_sum -= nums[window_start] window_start += 1 return 0 if min_length == float('inf') else min_length
Time Complexity:
Although there is a while loop inside the for loop, the time complexity is linear, not quadratic. The window_start and window_end pointers each move at most steps. Each element is added to the sum once and subtracted once. Therefore, the total operations are proportional to .
Space Complexity:
We only use a fixed number of variables (window_start, window_end, current_sum, min_length) regardless of the input size. No auxiliary data structures are used.
The Sliding Window - Variable Size (Condition-Based) pattern is highly reusable. Similar logic applies to:
k or check condition within a variable range.k.Why does the naive solution get TLE?
Why use a while loop instead of an if statement?
if (current_sum >= target) inside the for-loop.Why do I return 0 at the end?
min_length directly without checking if it was ever updated.target, the condition current_sum >= target is never met, and min_length remains at its initialized "infinity" value.INT_MAX or infinity instead of the required 0.Does this work with negative numbers?
nums contains negative values.