I came across a problem on a coding contest which basically boils down to this.
Given an unsorted array with positive numbers find the length of the smallest subarray which has a sum greater than or equal to an input sum
.
For input : [14, 2, 10, 1, 1, 2, 1]
And sum = 10
output = 1 [10]
for sum = 13
output = 1 [14]
for sum = 15
output = 2 [14, 2]
There will be a lot of queries to answer in the range of 1 to 10^5
.
My approach.
Build an array of the same length as the input where array[i]
will be the maximum sum of a subarray of size i
. This can be done in O(N * N)
time and O(N)
space
So now we have an array
with increasing sum
so we can use binary search to find the smallest length that can satisfy the particular input sum.
so if there were q
queries it would run in O(q * log(N))
time.
I'm not sure how feasible this solution is or if there is a better solution than this. Since I couldn't test it out on that online judge and the problem isn't available now.
Is there a better solution to this in terms of time and space complexity.
Follow up:
What if the given input can be changed later. How do you have such situations where the input can be updated.