Minimum Size Subarray Sum
Master this topic with zero to advance depth.
Minimum Size Subarray Sum
Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead.
Visual Representation
target = 7, nums = [2, 3, 1, 2, 4, 3]
[2, 3, 1, 2], 4, 3 (Sum: 8 >= 7, Len: 4)
2, [3, 1, 2, 4], 3 (Sum: 10 >= 7, Len: 4)
2, 3, 1, [2, 4, 3] (Sum: 9 >= 7, Len: 3) -> MINIMALExamples
Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
The subarray [4,3] has the minimal length under the problem constraint.
Approach 1
Level I: Brute Force (O(N^2))
Intuition
Check all possible subarrays and find the one with sum >= target and minimum length.
Thought Process
- Use two nested loops to define every subarray
nums[i...j]. - Calculate the sum of each subarray.
- If
sum >= target, updateminLen = min(minLen, j - i + 1).
Pattern: Subarray Enumeration
⏱ O(N^2)💾 O(1)
Approach 2
Level III: Optimal (Variable Sliding Window)
Intuition
Categorization
This is the classic Variable Size Window problem. We expand the window until the sum meets the target, then shrink from the left to find the smallest valid window.
Thought Process
- Maintain a
windowSumand aleftpointer. - Iterate
rightfrom 0 ton-1(Expand). - Add
nums[right]towindowSum. - While
windowSum >= target:- Update
minLenwithright - left + 1. - Subtract
nums[left]fromwindowSumand incrementleft(Shrink).
- Update
Mandatory Variables
left: Pointer to the start of the window.windowSum: Current sum of the window content.minLen: Smallest valid window length found.
⏱ O(N) - Each element is visited at most twice.💾 O(1)
Detailed Dry Run
| Step | L | R | windowSum | minLen | Action |
|---|---|---|---|---|---|
| 1 | 0 | 0 | 2 | inf | Expand |
| 2 | 0 | 1 | 5 | inf | Expand |
| 3 | 0 | 2 | 6 | inf | Expand |
| 4 | 0 | 3 | 8 | 4 | Sum >= 7! Update minLen, Shrink L |
| 5 | 1 | 3 | 6 | 4 | Sum < 7. Expand R |
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.