Minimum Size Subarray Sum
Given an array of positive integers numstargettarget0
Example 1
Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.
Example 2
Input: target = 4, nums = [1,4,4]
Output: 1
Output: 1
Example 3
Input: target = 11, nums = [1,1,1,1,1,1,1,1]
Output: 1
Output: 1
Constraints:
1 <= target <= 1091 <= nums.length <= 1051 <= nums[i] <= 104
Solution 1 - Using sliding window technique, keep track of minimum window size where the sum of elements are greater than or equal to target
In this approach, we are going to apply sliding window technique using two pointers leftrighttarget
Implementation steps:
-
First, create four variables
,left that we will use to adjust the window,right to store sum of elements in current window, andsum to hold the answer,initializemin with input arrray length +1, as the minimum will be less than the array size.min -
Next, run a
loop untilwhile pointer reaches end of input arrayright , and do the following:nums-
Take the current element from
, and add it to thenums .sum -
Next, check if we are going out of bounds, that is check if the
is greater than or equal tosum , then capture the window size and store it intarget , if it is less than any of the previousmin that was found.min -
Also, move the
pointer, and subtract the value atleft pointer fromleft since we are moving the sliding window.sum -
At the end of while loop increment
pointer to move to the next element in input arrayright .nums
-
Take the current element from
-
Finally, check if there is any minimum value found, i.e. check if
is still has the initialized value (min ), if it is then return '0', otherwise returnnums.length +1 .min
Java
public class MinimumSizeSubArraySum {
static int minSubArrayLen(int target, int[] nums) {
int left = 0;
int right = 0;
int sum =0;
int min = nums.length + 1;
while(right < nums.length) {
sum += nums[right];
while(sum >=target) {
min = Math.min(right - left +1 , min);
sum-=nums[left];
left++;
}
right++;
}
return min == nums.length +1 ? 0 : min;
}
public static void main(String[] args) {
System.out.println(minSubArrayLen(7, new int[]{2,3,1,2,4,3}));
System.out.println(minSubArrayLen(11, new int[]{1,1,1,1,1,1,1,1}));
}
}
Complexity Analysis:
Time complexity: Above code runs in O(n) time, where nnums
Space complexity: O(1).
Above implementations source code can be found at