Smallest Subarray with a given Sum
Sliding Window
Problem
Given an array of positive numbers and a positive number ‘S,’ find the length of the smallest contiguous subarray whose sum is greater than or equal to ‘S’. Return 0 if no such subarray exists.
For example:
Thought Process
We will use a dynamic window (adjust size as we go depending on condition)
The condition that will determine our window size is if the total sum is greater than the s, if this is true then we will continually shrink our window till the total sum is less than s.
Solution
Key Points
Using a dynamic window
When the total sum of a contigous subarray is greater than s is when we start to shrink our window
Time Complexity
Time: because the outer
for
loop runs for all elements, and the innerwhile
loop processes each element only once; therefore, the time complexity of the algorithm will be , which is asymptotically equivalent to .Space: O(1)
Last updated
Was this helpful?