Leetcode 209. Minimum Size Subarray Sum
Given an array of positive integers nums
and a positive integer target
, return the minimal length of a contiguous subarray [nums[l], nums[l+1], ..., nums[r-1]]
of which the sum is greater than or equal to target
. If there is no such subarray, return 0
instead.
n
) can be up to 10^5
and the value of each element in the array can be up to 10^4
.We can solve this problem using the sliding window (or two-pointer) technique:
left
and right
, both at the beginning of the array.right
pointer to the right and adding the elements to current_sum
until current_sum
becomes greater than or equal to target
.current_sum
is greater than or equal to target
, move the left
pointer to the right to shrink the window. After each move, update the minimum length of the subarray and subtract the element at left
from current_sum
.right
pointer reaches the end of the array.0
.public class Solution {
public int minSubArrayLen(int target, int[] nums) {
int n = nums.length;
int left = 0;
int currentSum = 0;
int minLength = Integer.MAX_VALUE;
for (int right = 0; right < n; right++) {
currentSum += nums[right];
while (currentSum >= target) {
minLength = Math.min(minLength, right - left + 1);
currentSum -= nums[left];
left++;
}
}
return (minLength == Integer.MAX_VALUE) ? 0 : minLength;
}
}
n
is the number of elements in the array. Each element is processed at most twice (once by right
pointer and once by left
pointer).This sliding window approach is efficient and suitable for the input constraints given in the problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?