Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 17477

Edge case of binary subarray with sum

$
0
0

Problem
Given a binary array nums and an integer goal, return the number of non-empty subarrays with a sum goal.

Link to the problem

Code

class Solution:    def numSubarraysWithSum(self, nums, goal):        count,i,j,sumSoFar=0,0,0,0        N=len(nums)        while j < N:            if sumSoFar==goal:                print('my solution is [' , i , j , ']')                count+=1                sumSoFar+=nums[j]                j+=1            elif sumSoFar > goal:                sumSoFar-=nums[i]                i+=1            else:                sumSoFar+=nums[j]                j+=1        while i < N:            if sumSoFar == goal:                count+=1            sumSoFar-=nums[i]            i+=1        return countsolution = Solution()array = [1,0,1,0,1]goal = 2a = solution.numSubarraysWithSum(array,goal) #expected 4print(a) # Output: 4array = [0,0,0,0,0]goal = 0a = solution.numSubarraysWithSum(array,goal) #expected 15print(a) # Output: 10

Issue
when j == N it stops but it has other subarrays to consider like if you considernums=[0,0,0,0] and goal=0 you see that it doesnt consider cases from index 2-3 or 1-3 inclusive. When i have a case of [0,0,0,0,0] and i figure out my sumSoFar == 0 at i=0 j=1 ([0,0] as subarray) i dont know how to move forward because if i move forward with i, its a possible subarray and if i move forward with j its a possible subarray. I have to pick one and thus i am missing out on other possible sub arrays and my count is lower than it should be.


Viewing all articles
Browse latest Browse all 17477

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>