Binary Subarrays With Sum — LeetCode 930 Python Solution

MediumArrayHash TablePrefix SumSliding Window
Problem
#930
Reading time
2 min

The problem

Given a binary array nums and an integer goal, return the number of non-empty subarrays with a sum goal. A subarray is a contiguous part of the array.

Example

Input
nums = [1,0,1,0,1], goal = 2
Output
4
Explanation
The 4 subarrays are bolded and underlined below:

Python solution

Python
class Solution:
    def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:
        cnt = Counter({0: 1})
        ans = s = 0
        for v in nums:
            s += v
            ans += cnt[s - goal]
            cnt[s] += 1
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 930. Binary Subarrays With Sum is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 930. Binary Subarrays With Sum?
LeetCode 930. Binary Subarrays With Sum is rated Medium on LeetCode.
What is the time complexity of LeetCode 930. Binary Subarrays With Sum?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 930. Binary Subarrays With Sum?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 930. Binary Subarrays With Sum cover?
LeetCode 930. Binary Subarrays With Sum is tagged Array, Hash Table, Prefix Sum and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview