Minimum Size Subarray Sum

Problem: Minimum Size Subarray Sum

We can use a sliding window implemented by two pointers to solve this question. The window can start from head of the list. If the sum in the window is smaller than target, we extend our sliding window to right. If the sum in the window is bigger or equal to the target, we update our minimum size and reduce the window by moving left boundary to right until the sum is smaller than target again.

Code in Python:

class Solution(object):
    def minSubArrayLen(self, s, nums):
        """
        :type s: int
        :type nums: List[int]
        :rtype: int
        """
        if not nums: return 0
        i, j, sum, ans = 0, 0, 0, 0
        while j < len(nums):
            sum += nums[j]
            if sum < s: j += 1
            else:
                ans = min(ans, j-i+1) if ans else j-i+1
                if ans == 1: return 1
                sum -= nums[i] + nums[j]
                i += 1
        return ans

results matching ""

    No results matching ""