Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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 1:
Input: nums = [1,0,1,0,1], goal = 2 Output: 4 Explanation: The 4 subarrays are bolded and underlined below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1]
Example 2:
Input: nums = [0,0,0,0,0], goal = 0 Output: 15
Constraints:
1 <= nums.length <= 3 * 104nums[i] is either 0 or 1.0 <= goal <= nums.lengthProblem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Sliding Window
[1,0,1,0,1] 2
[0,0,0,0,0] 0
count-subarrays-with-score-less-than-k)ways-to-split-array-into-good-subarrays)find-all-possible-stable-binary-arrays-i)find-all-possible-stable-binary-arrays-ii)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #930: Binary Subarrays With Sum
class Solution {
public int numSubarraysWithSum(int[] nums, int goal) {
int[] cnt = new int[nums.length + 1];
cnt[0] = 1;
int ans = 0, s = 0;
for (int v : nums) {
s += v;
if (s - goal >= 0) {
ans += cnt[s - goal];
}
++cnt[s];
}
return ans;
}
}
// Accepted solution for LeetCode #930: Binary Subarrays With Sum
func numSubarraysWithSum(nums []int, goal int) (ans int) {
cnt := map[int]int{0: 1}
s := 0
for _, v := range nums {
s += v
ans += cnt[s-goal]
cnt[s]++
}
return
}
# Accepted solution for LeetCode #930: Binary Subarrays With Sum
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
// Accepted solution for LeetCode #930: Binary Subarrays With Sum
struct Solution;
impl Solution {
fn num_subarrays_with_sum(a: Vec<i32>, s: i32) -> i32 {
let n = a.len();
let mut count = vec![0; n + 1];
count[0] = 1;
let mut sum = 0;
let mut res = 0;
for i in 0..n {
sum += a[i];
if sum >= s {
res += count[(sum - s) as usize];
}
count[sum as usize] += 1;
}
res as i32
}
}
#[test]
fn test() {
let a = vec![1, 0, 1, 0, 1];
let s = 2;
let res = 4;
assert_eq!(Solution::num_subarrays_with_sum(a, s), res);
}
// Accepted solution for LeetCode #930: Binary Subarrays With Sum
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #930: Binary Subarrays With Sum
// class Solution {
// public int numSubarraysWithSum(int[] nums, int goal) {
// int[] cnt = new int[nums.length + 1];
// cnt[0] = 1;
// int ans = 0, s = 0;
// for (int v : nums) {
// s += v;
// if (s - goal >= 0) {
// ans += cnt[s - goal];
// }
// ++cnt[s];
// }
// return ans;
// }
// }
Use this to step through a reusable interview workflow for this problem.
For each starting index, scan the next k elements to compute the window aggregate. There are n−k+1 starting positions, each requiring O(k) work, giving O(n × k) total. No extra space since we recompute from scratch each time.
The window expands and contracts as we scan left to right. Each element enters the window at most once and leaves at most once, giving 2n total operations = O(n). Space depends on what we track inside the window (a hash map of at most k distinct elements, or O(1) for a fixed-size window).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.