What it teaches: The "shortest" variant: shrink while the window is valid, recording its length each time.
Practise it on judges as “Minimum Size Subarray Sum”.
The problem
Given an array of positive integers nums and a positive target, return the minimal length of a contiguous subarray whose sum is at least target, or 0 if there's none.
→ "Minimal length" contiguous subarray with a sum condition
→ All positive → shrinking always lowers the sum
These clues point to Sliding Window: Variable Size: Grow the window with the right pointer; when it breaks a rule, shrink it from the left until it's valid again.
Stuck? Take one hint at a time
Solution.java · starter
class Solution {
public int minSubArrayLen(int target, int[] nums) {
return 0;
}
}
Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.
Step 1/4Grow to [2, 3, 1, 2]: sum 8 ≥ 7. Record 4, then remove 2: sum 6 < 7.
Approach 1
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int left = 0, sum = 0, best = Integer.MAX_VALUE;
for (int right = 0; right < nums.length; right++) {
sum += nums[right];
while (sum >= target) {
best = Math.min(best, right - left + 1);
sum -= nums[left++];
}
}
return best == Integer.MAX_VALUE ? 0 : best;
}
}
Verdict: Each element enters and leaves once.
Before you submit
Edge cases and common mistakes
Test these inputs
No valid subarray → 0
A single element ≥ target → 1
The whole array needed
Mistakes people make
Returning Integer.MAX_VALUE when nothing is found.