pythonalgorithmlogicsliding-window

what is going wrong in Minimum size subarray sum end condition


Problem

Given an array of positive integers nums and a positive integer target, return minimal length of subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.

Link to the problem: 209. Minimum size subarray sum

Some examples:

nums = [2,3,1,2,4,3] target = 7 output = 2 
nums = [1,4,4] target = 4 output = 1 
nums = [1,1,1,1,1,1,1,1] target = 11 output = 0 

My thought process

class Solution(object):
    def minSubArrayLen(self, target, nums):
        i,j,sumSoFar=0,0,0
        N = len(nums)
        if N == 0:
            return 0
        min_len=float('inf')
        while j < N:
            if sumSoFar >= target:
                min_len = min(j-i, min_len)
                sumSoFar-=nums[i]
                i+=1
            else: #sumSoFar is less than target
                sumSoFar+=nums[j]
                j+=1
        if min_len == float('inf'):
            return 0
        return min_len

Issue

While trying to solve by hand in the first case (nums = [2,3,1,2,4,3], target = 7), I reach j=6 before I can check for [3,4] as a possible solution because j == N/6. Also I feel like when I go to the if condition I add nums[j] two times (at j=3).

What am I doing wrong?


Solution

  • Your thinking is good, but the loop will end when j reaches N, which prevents you from finding a legitimate subarray at the end of nums. Adding or sumSoFar >= target to the loop condition will allow the algorithm to continue in that case.

    Here's a working solution:

    from math import inf
    
    class Solution(object):
        def minSubArrayLen(self, target, nums):
            i=0
            j=0
            min_len = inf
            sumSoFar=0
    
            while j < len(nums) or sumSoFar >= target:
                if sumSoFar >= target:
                    min_len = min(min_len, j - i)
                    sumSoFar -= nums[i]
                    i += 1
                else:  # sumSoFar is less than target
                    sumSoFar += nums[j]
                    j += 1
            return min_len if min_len != inf else 0
    

    Example: Solution().minSubArrayLen(7, [2, 3, 1, 2, 4, 3]) # 2