Back to Arrays & Hashing
Arrays & Hashing
Medium

Binary Subarrays With Sum

LAB

Given a binary array, return the number of contiguous subarrays with sum equal to goal.

EXAMPLES

Example 1
Input
{
  "nums": [
    1,
    0,
    1,
    0,
    1
  ],
  "goal": 2
}

Output
4

FUNCTION SHAPE

nums: intArraygoal: intint
SOLUTION NOTE

Notice that this is actually just an easier case of Q560 Subarray Sum Equals K. The exact same code works here.

Reveal reference solution +
pythonREFERENCE
# This is just an easier case of Q560 - exact same code works!
def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:
    return self.subarraySum(nums, goal)
TimeO(n)
SpaceO(n)
Open on LeetCode
00:00
3 local tests readyRun with ⌘/Ctrl + Enter. Your code stays in this browser.

Runs solve(...) locally in a browser worker. SWE Playbook does not submit your code. Only run code you trust; Python code may access the network.