Minimum Size Subarray Sum
Minimum Size Subarray Sum
Given an array of positive integers nums and a target sum, return the minimal length of a contiguous subarray whose sum is at least the target. If there is no such subarray, return 0.
Because all numbers are positive, a sliding window works in O(n).
Function signature
func MinSubArrayLen(target int, nums []int) int
Inputs / outputs
target: required minimum sum.nums: slice of positive integers.- Return: minimal subarray length, or 0 if none.
Example
nums = [2,3,1,2,4,3], target = 7
Output: 2
Reason: [4,3] is the shortest window with sum >= 7.
Constraints
0 <= len(nums) <= 100_0001 <= nums[i] <= 1_000_000_0001 <= target <= 1_000_000_000
Core idea (near-solution)
Use a sliding window [l, r] with a running sum.
- Expand
rto increase the sum. - When the sum is >= target, shrink from the left to find the minimal window.
Invariant: the sum always equals the elements inside the current window.
Algorithm (step-by-step)
- Initialize
l = 0,sum = 0,best = +infinity. - For each
rfrom 0 tolen(nums)-1:- Add
nums[r]tosum. - While
sum >= target:- Update
best = min(best, r-l+1). - Subtract
nums[l]fromsumand incrementl.
- Update
- Add
- If
bestwas never updated, return 0; otherwise returnbest.
Correctness sketch
- Invariant: the sum always equals the elements inside the current window.
- The window state exactly matches the elements in
s[l..r]. - Shrinking/expanding preserves validity, so any recorded window is correct.
- The best recorded window is optimal because all candidate windows are considered.
Trace (hand walkthrough)
Trace Walkthrough
Example input:
nums = [2,3,1,2,4,3], target = 7
Output: 2
Reason: [4,3] is the shortest window with sum >= 7.
Walk:
- r=0 sum=2; r=1 sum=5; r=2 sum=6
- r=3 sum=8 >=7 -> min=4, shrink: drop 2 -> sum=6, l=1
- r=4 sum=10 >=7 -> min=4, drop 3 -> sum=7, l=2 -> min=3; drop 1 -> sum=6, l=3
- r=5 sum=9 >=7 -> min=3, drop 2 -> sum=7, l=4 -> min=2; drop 4 -> sum=3
Pitfalls to avoid
- Forgetting to shrink while
sum >= target(must be a loop, not an if). - Using this approach if numbers can be negative (it breaks the invariant).
Complexity
- Time:
O(n) - Extra space:
O(1)
Implementation notes (Go)
- Maintain
sumandleft; shrink whilesum >= target. - Track the smallest window; return 0 if no valid window.
Run tests to see results
No issues detected