Minimum Size Subarray Sum – Solution & Complexity
Solution Walkthrough
1. Understand the Goal
- Find the length of the shortest contiguous run of
numswhose sum is >=target, or 0 if no run reaches it. - All values are positive — that constraint is what makes a sliding window valid here instead of needing prefix sums with binary search.
2. Choose the Core Pattern
- Variable-size sliding window with two pointers: because every element is positive, the running window sum is monotonic in both directions — growing the window (moving
right) can only increase the sum, and shrinking it (movingleft) can only decrease it. - That monotonicity is exactly what breaks with negative values: shrinking the window could increase the sum instead (removing a negative number raises the total), so the greedy "shrink while sum is big enough" rule would no longer be safe, and you'd need a different technique (e.g. prefix sums with a monotonic deque, since binary search alone doesn't work either once prefix sums stop being non-decreasing).
3. Build the Algorithm
- Expand the window by moving
rightacross every index once, addingnums[right]to a runningwindowSum. - After each addition, while
windowSum >= target, the current window is a valid candidate: record its length if it's the best seen so far, then shrink from the left by subtractingnums[left]and advancingleft— shrinking is always safe to attempt again immediately, since the sum only goes down and might still satisfy>= target. - Because
leftonly ever advances and never resets backward, each index is added to the sum once and removed at most once, giving O(n) total work despite the nested loop.
4. Check Edge Cases
- No subarray reaches
target(e.g. all values are 1 andtargetexceeds the total sum): the inner while loop never triggers, and the best-length sentinel must be recognized and converted to 0 in the return value. - The entire array is required (e.g.
targetequals the whole array's sum, achieved only once at the end): the window must be allowed to grow all the way toright == len(nums) - 1before it first becomes valid. - A single element already meets
target: the window shrinks immediately back down to length 1 on the same iteration it became valid.
5. Final Solution and Complexity
- Time complexity is O(n).
- Space complexity is O(1).