MEDIUM Sliding Window
209. Minimum Size Subarray Sum
๐ Problem
Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขString/array indexing
- โขSet/Map frequency counting
- โขPointer movement invariants
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply Sliding Window reasoning pattern
- โขApply Two Pointers reasoning pattern
๐ก Approach
- โ Use sliding window with left and right pointers
- โ Expand window by moving right pointer
- โ When sum >= target, shrink from left and track minimum length
- โ All numbers are positive, so shrinking won't increase sum
- โ Time: O(n), Space: O(1)
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse sliding window with left and right pointers
- โขExpand window by moving right pointer
- โขWhen sum >= target, shrink from left and track minimum length
Common Pitfalls
- โขAll numbers are positive, so shrinking won't increase sum
- โขTime: O(n), Space: O(1)
๐งช Test Cases
Hidden tests on submit: 2
Test Case 1
Not run Input:
minSubArrayLen(7, [2,3,1,2,4,3]); Expected:
2 Test Case 2
Not run Input:
minSubArrayLen(4, [1,4,4]); Expected:
1 Test Case 3
Not run Input:
minSubArrayLen(11, [1,1,1,1,1,1,1,1]); Expected:
0 ๐ Code Editor
๐ค Output