Skip to contentKEEP THE CRAFTTHE SANCTUARY

Binary Subarrays With Sum

Count subarrays of 0s and 1s that add up to goal, using prefix sums and a dictionary of counts.

The problem

Implement Solution.numSubarraysWithSum(nums, goal). nums contains only 0s and 1s. Return how many non-empty contiguous subarrays have a sum equal to goal. For example, nums = [1, 0, 1, 0, 1] and goal = 2 returns 4. 1 <= len(nums) <= 30000 and 0 <= goal <= len(nums).

Starter code

class Solution:
    def numSubarraysWithSum(self, nums, goal):
        pass

Public examples

  1. nums = [1, 0, 1, 0, 1], goal = 2gives4
  2. nums = [1], goal = 1gives1
  3. nums = [0, 0], goal = 1gives0

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.