Minimum Size Subarray Sum
Given an array of positive integers
nums and a positive integer
target, return the minimal length of a contiguous subarray
[numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to
target. If there is no such subarray, return
Input: target = 7, nums = [2,3,1,2,4,3]
Explanation: The subarray [4,3] has the minimal length under the problem constraint.
Input: target = 4, nums = [1,4,4]
Input: target = 11, nums = [1,1,1,1,1,1,1,1]
1 <= target <= 109
1 <= nums.length <= 105
1 <= nums[i] <= 105
We could keep 2 pointers ,one for the start and another for the end of the current subarray, and make optimal moves so as to keep the sum greater than s as well as maintain the lowest size possible.
- Initialize left pointer to 0 and sum to 0
- Iterate over the nums:
- Add nums[i] to sum.
- While sum is greater than or equal to s:
- Update result=min(result,i+1−left), where i+1−left is the size of current subarray.
- It means that the first index can safely be incremented, since, the minimum subarray starting with this index with sum≥s has been achieved
- Subtract nums[left] from sum and increment left.
- Time complexity: O(n). Single iteration .
- Space complexity: O(1) extra space.
If you like the content please follow me here @medium and at LinkedIn