Intuition
We are required to find the length of the smallest subarray whose sum is greater than or equal to target
.
A naieve approach to this is to check all subarrays to see if their sum equals target. That would be .
A more optimized approach would be to move a variable size sliding window over our array and check the sum of our current sliding window. Here a technical challenge is, how will we obtain the sum of the variable sliding window.
Well, there are two approaches - we can have a variable cur_sum
and add the elements that enter into the window to it. Also, subtract elements from cur_sum
as they go out of the window.o
Another approach is to have a prefix sum array which helps us compute range/subarray sums in constant time. The former approach is more desirable here since the prefix array will require memory while the former approach is constant memory.
Code
Python3 (compute running sum)
Python3 (using a prefix array for constant time range sums)
Big O Analysis
-
Runtime
The runtime complexity here is since we are traversing every element once.
-
Memory
The memory usage is since we are not using any extra data structure. for the prefix sum approach.
— A