Leetcode 209 Minimum Size Subarray Sum

Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, …, numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead.

Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.
Input: target = 4, nums = [1,4,4]
Output: 1
  • Have two pointers, one fast, one slow to move to the right. Keep moving the faster pointer to the right as long as the sum is less than the target. Subtract the slower pointer pointing number when every time moving the slower pointer.
class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        if target > sum(nums):
            return 0
        left = right = 0
        running_sum = 0
        result = sys.maxsize
        n = len(nums)
        
        while right < n:
            running_sum +=nums[right]
            
            while running_sum >= target:
                result = min(result,right - left + 1)
                running_sum -= nums[left]
                left +=1
            
            right +=1
        
        return result