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:
Input: [2, 1, 5, 2, 3, 2], S=7
Output: 2
Explanation: The smallest subarray with a sum
great than or equal to '7' is [5, 2].Input: [2, 1, 5, 2, 8], S=7
Output: 1
Explanation: The smallest subarray with a sum
greater than or equal to '7' is [8].Input: [3, 4, 1, 1, 6], S=8
Output: 3
Explanation: Smallest subarrays with a sum
greater than or equal to '8' are [3, 4, 1]
or [1, 1, 6].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: O(N) because the outer
forloop runs for all elements, and the innerwhileloop processes each element only once; therefore, the time complexity of the algorithm will be O(N+N) , which is asymptotically equivalent to O(N).Space: O(1)
Last updated