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

def smallest_subarray_with_given_sum(s, nums):
        minWindow = float("inf")
        totalSum = 0
        start = 0
        
        
        for i in range(len(nums)):
            totalSum+=nums[i]
            while totalSum >= s:
                minWindow = min(minWindow, i+1-start)
                totalSum-=nums[start]
                start+=1
        if minWindow == float("inf"):
            return 0
        return minWindow

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)O(N) because the outer for loop runs for all elements, and the inner while loop processes each element only once; therefore, the time complexity of the algorithm will be O(N+N)O(N+N) , which is asymptotically equivalent to O(N)O(N).

  • Space: O(1)

Last updated

Was this helpful?