Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
For example, given the array [2,3,1,2,4,3]
and s = 7
,
the subarray [4,3]
has the minimal length under the problem constraint.
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Intuition
Do as directed in question. Find the sum for all the possible subarrays and update the as and when we get a better subarray that fulfill the requirements ().
Algorithm
Complexity Analysis
Time complexity: .
Space complexity: extra space.
Intuition
In Approach #1, you may notice that the sum is calculated for every surarray in time. But, we could easily find the sum in O(1) time by storing the cumulative sum from the beginning(Memoization). After we have stored the cumulative sum in , we could easily find the sum of any subarray from to .
Algorithm
Complexity analysis
Time complexity: .
Space complexity: extra space.
Intuition
We could further improve the Approach #2 using the binary search. Notice that we find the subarray with starting with an index in time. But, we could reduce the time to using binary search. Note that in Approach #2, we search for subarray starting with index , until we find that is greater than . So, instead of iterating linearly to find the sum, we could use binary search to find the index that is not lower than in the , which can be done using function in C++ STL or could be implemented manually.
Algorithm
Create vector of size with :
Iterate from to :
Complexity analysis
Intuition
Until now, we have kept the starting index of subarray fixed, and found the last position. Instead, we could move the starting index of the current subarray as soon as we know that no better could be done with this index as the starting index. We could keep 2 pointer,one for the start and another for the end of the current subarray, and make optimal moves so as to keep the greater than as well as maintain the lowest size possible.
Algorithm
Complexity analysis
Analysis written by @abhinavbansal0.