Binary Subarrays With Sum

MediumSliding Windowprefix sum

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an array nums in which every element is 0 or 1, and an integer goal. Return how many non-empty contiguous subarrays have a sum exactly equal to goal. Note that goal may be 0, in which case runs of zeros count. Aim for O(n) time.

Examples

Input: nums = [0,1,0,1], goal = 1
Output: 6
Four subarrays contain only the first 1 ([0,1], [1], [0,1,0], [1,0]) and two contain only the second 1 ([0,1], [1]).
Input: nums = [0,0,0], goal = 0
Output: 6
Every one of the 3 + 2 + 1 subarrays sums to 0.

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • `nums[i]` is 0 or 1
  • 0 <= goal <= nums.length

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More prefix sum problems