Binary Subarrays With Sum solution explained

Binary Subarrays With Sum asks how many contiguous runs of a 0/1 array add up to a target. Count prefix sums in a hash map, adding the number of earlier prefixes equal to the current prefix minus the target, or count windows with at most target ones and subtract the windows with at most target minus one. Both run in O(n).

By Published 7 min read

The problem in plain words

You get an array where every element is 0 or 1, and a whole number called the target. Count the contiguous slices (at least one element long) whose elements add up to exactly the target. Two slices count separately whenever they start or end at different positions, even if they look the same.

Arrays made up for this page; answers computed by the code below
ArrayTargetCountWhy
[1, 0, 0, 1, 0, 1]25Slices with exactly two 1s; the zeros around them multiply the choices
[0, 0, 0]06Every slice of an all-zero array sums to 0: 3 + 2 + 1
[1, 1, 1]13Only the three single-element slices
[1, 0, 1]30There are only two 1s in total
[0, 1, 0, 0]16Pick where to start in the first two cells and where to end in the last three
Arrays made up for this page; answers computed by the code below. Scroll sideways on a small screen.

What the interviewer is looking for

This is a counting problem in a window's clothing. Many candidates reach for a sliding window, see it miscount, and get stuck. The interviewer wants to see you explain why zeros break the simple window, then reach either prefix-sum counting (the same idea as Two Sum, applied to running totals) or the trick of counting "at most" twice. Being able to give both is a strong signal.

Brute force: extend from every start

Pick each starting index, walk right while keeping a running sum, and count each time the sum equals the target. Because values are never negative, once the sum passes the target it can only grow, so you may stop that start early. That helps on arrays full of 1s, but an array of zeros with target 0 still touches every pair: O(n²).

def count_slow(bits, goal):
    n = len(bits)
    total = 0
    for i in range(n):
        running = 0
        for j in range(i, n):
            running += bits[j]
            if running == goal:
                total += 1
            elif running > goal:
                break
    return total
Reference version: O(n²) time, O(1) space.

Approach 1: count matching prefix sums

Let prefix(r) be the sum of the first r elements. The slice from position l to r - 1 sums to prefix(r) - prefix(l). So a slice ending just before position r hits the target exactly when some earlier prefix equals prefix(r) - target. Walk the array once, keep a map from each prefix value to how many times it has appeared, and at each step add the count stored for prefix - target. Seed the map with prefix 0 seen once, which stands for the empty start and lets slices that begin at index 0 count.

def count_with_prefix(bits, goal):
    seen = {0: 1}  # prefix sum -> how many times it has appeared
    prefix = 0
    total = 0
    for b in bits:
        prefix += b
        total += seen.get(prefix - goal, 0)
        seen[prefix] = seen.get(prefix, 0) + 1
    return total
Prefix-sum counting: O(n) time, O(n) space for the map.

Since a 0/1 array's prefix sums only range from 0 to n, a plain list of length n + 1 can replace the dictionary. This version also works unchanged for arrays with any integers, including negatives, which makes it the safer one to lead with if the interviewer later relaxes the 0/1 rule.

Approach 2: at most target, minus at most target - 1

A sliding window is great at counting slices whose sum is at most some limit: grow the right edge, shrink the left edge while the sum is too big, and then every slice ending at the right edge and starting anywhere from left to right is valid, which is right - left + 1 slices. Exactly target is then "at most target" minus "at most target - 1". The subtraction leaves only the slices whose sum is exactly the target, and the window needs no map.

def at_most(bits, limit):
    if limit < 0:
        return 0
    left = 0
    ones = 0
    total = 0
    for right, b in enumerate(bits):
        ones += b
        while ones > limit:
            ones -= bits[left]
            left += 1
        total += right - left + 1  # every window ending at right
    return total

def count_with_windows(bits, goal):
    return at_most(bits, goal) - at_most(bits, goal - 1)
Two window passes: O(n) time, O(1) space.
function countBinarySubarrays(bits, goal) {
  const atMost = (limit) => {
    if (limit < 0) return 0;
    let left = 0, ones = 0, total = 0;
    for (let right = 0; right < bits.length; right++) {
      ones += bits[right];
      while (ones > limit) ones -= bits[left++];
      total += right - left + 1;
    }
    return total;
  };
  return atMost(goal) - atMost(goal - 1);
}
JavaScript: the same window trick, with the helper as a closure.

Why a single window miscounts

Try a one-window version on [0, 1, 0, 0] with target 1. When the right edge reaches the last 0, the window holds one 1, but the slices ending there with sum 1 start at index 0 or index 1. A window that only tracks one left edge records one of them. The zeros at the front create a range of valid starts, and the "at most" formulation counts a range (right - left + 1) instead of a single start, which is why it works.

Trace on the first example

For [1, 0, 0, 1, 0, 1] and target 2, the prefixes after each element are 1, 1, 1, 2, 2, 3. At the fourth element the prefix is 2, and prefix 0 has been seen once, so 1 slice ends there. At the fifth, prefix 2 again: 1 more. At the sixth, prefix 3, and prefix 1 has been seen three times: 3 more. Total 5.

Complexity

n is the array length
ApproachTimeExtra spaceHandles negatives?
Extend from every startO(n²)O(1)Only without the early break
Prefix sums in a mapO(n)O(n)Yes
At most k minus at most k - 1O(n)O(1)No: shrinking assumes sums only grow
n is the array length. Scroll sideways on a small screen.

Edge cases

  • Target 0: count runs of zeros. A run of length m contributes m(m + 1)/2. Both approaches handle it, and the window version relies on at_most(-1) returning 0.
  • Target larger than the number of 1s: the answer is 0.
  • Empty array: 0.
  • All ones: exactly n - target + 1 slices when 1 ≤ target ≤ n.

Mistakes to avoid

  • Forgetting to seed the map with prefix 0 seen once, which drops every slice starting at index 0.
  • Updating the map before looking up prefix - target. With target 0 that counts the empty slice ending at each position.
  • Using one window and moving the left edge greedily, which undercounts whenever zeros sit at the left edge.
  • Calling the window method with target - 1 = -1 and letting the loop run; guard it or it shrinks past the right edge.

How to explain it out loud

Fictional example

A two-minute spoken answer
Candidate
Brute force checks every start and extends right; that's quadratic, and zeros stop me from breaking early.
Candidate
A slice sums to the target when two prefix sums differ by the target. So I keep counts of prefixes seen so far and, at each step, add how many equal the current prefix minus the target. One pass, a map of at most n + 1 keys.
Candidate
If you want constant space: windows with at most k ones are easy to count, so exactly k is at-most-k minus at-most-k-minus-one.

The fixed-size window in Minimum Swaps to Group All 1's Together also counts 1s inside a window, and Get Equal Substrings Within Budget uses the same grow-and-shrink loop with a cost instead of a count. Longest Substring Without Repeating Characters is the classic introduction to variable windows. More on the coding problems hub.

Practicing it with Natively

In a practice session on Mac or Windows, Natively can read this prompt from a screenshot and talk through why the zeros break a single window, or check your prefix-map code for the off-by-one in the seed. Its transcript of your mock lets you hear whether your explanation of "at most minus at most" was clear. See the AI interview assistant page.

Questions people ask

How do you solve Binary Subarrays With Sum?

Keep counts of prefix sums seen so far, starting with prefix 0 seen once. At each element, add the count of prefixes equal to the current prefix minus the target. It runs in O(n).

Why doesn't a normal sliding window work for Binary Subarrays With Sum?

Zeros let many different start positions give the same sum, and a single window tracks only one start. Counting windows with at most k ones handles a range of starts, so exactly k equals at most k minus at most k - 1.

What is the space complexity of Binary Subarrays With Sum?

The prefix-sum method uses O(n) extra space for the counts. The at-most-k window method uses O(1) extra space.

Does the prefix-sum method work with negative numbers?

Yes. Prefix-sum counting does not assume values are non-negative, so it also solves the general subarray-sum-equals-k problem. The window method does not.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP