Skip to main content

Minimum Size Subarray Sum

Question

Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.

Example 1
Input: s = 7, nums = [2,3,1,2,4,3]

Output: 2 (Subarray with minimum length is [4,3])

Solution

all//Minimum Size Subarray Sum.py


#Minimum Size Subarray Sum Algorithm

#given an array of n positive integers and a positive integer s,
#find the minimal length of a contiguous subarray of which the sum ≥ s.
#If there isn't one, return 0 instead.

def minSubArrayLen(nums, s):

min_length = float('inf')
left = 0
total = 0

for right in range(len(nums)):

total += nums[right]

while (total >= s):

min_length = min(min_length, right - left + 1)
total -= nums[left]
left += 1

if min_length == float('inf'):
return 0

return min_length

# Driver code
nums = [2, 3, 1, 2, 4, 3]
s = 7
print(minSubArrayLen(nums, s))