Given an array of positive integers
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.
Output: 1
Output: 1
Constraints:
1 <= target <= 109 1 <= nums.length <= 105 1 <= nums[i] <= 104
Contents
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
Implementation steps:
-
First, create four variables
left ,right that we will use to adjust the window,sum to store sum of elements in current window, andmin to hold the answer,initializemin with input arrray length +1, as the minimum will be less than the array size. -
Next, run a
while loop untilright pointer reaches end of input arraynums , and do the following:-
Take the current element from
nums , and add it to thesum . -
Next, check if we are going out of bounds, that is check if the
sum is greater than or equal totarget , then capture the window size and store it inmin , if it is less than any of the previousmin that was found. -
Also, move the
left pointer, and subtract the value atleft pointer fromsum since we are moving the sliding window. -
At the end of while loop increment
right pointer to move to the next element in input arraynums .
-
Take the current element from
-
Finally, check if there is any minimum value found, i.e. check if
min is still has the initialized value (nums.length +1 ), if it is then return '0', otherwise returnmin .
Complexity Analysis:
Time complexity: Above code runs in O(n) time, where
Space complexity: O(1).
Above implementations source code can be found at