⚡Flashcard Drill➔
NeetCode #243LC-930MediumSliding Window
← Back to All Problems

#243 · #930 · Binary Subarrays With Sum(和相同的二元子数组)

📌 Problem Statement & Constraints

Given a binary array nums and an integer goal, return the number of non-empty subarrays with a sum equal to goal. Constraints: 1 <= nums.length <= 3 * 10^4, 0 <= goal <= nums.length.

💡 Core Algorithmic Approaches

  1. Counting subarrays with exactly goal ones is awkward directly, but counting those with at most goal ones is a clean sliding window.
  2. Define atMost(g): the window is valid while its sum is at most g, and each right endpoint contributes r - l + 1 subarrays (all start positions in the valid window).
  3. Then the answer is atMost(goal) - atMost(goal - 1).
  4. This "exactly k = at most k minus at most k-1" pattern is a general technique worth remembering.

💻 Benchmark Python3 Implementation

class Solution:
    def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:
        def atMost(g: int) -> int:
            if g < 0:
                return 0               # no subarray can have a negative sum
            l = 0
            cur = 0
            res = 0
            for r, x in enumerate(nums):
                cur += x
                while cur > g:
                    cur -= nums[l]
                    l += 1
                res += r - l + 1       # all starts in the window are valid
            return res

        return atMost(goal) - atMost(goal - 1)

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): two linear passes, since each pointer moves monotonically within each call.
💾 Space Complexity
O(1): a few scalars.

⚠️ Interview Pitfalls & Follow-ups

  • Using a plain sliding window for the exact count: the window is not uniquely determined by "sum == goal" at each right endpoint, so the subtraction trick is needed.
  • Forgetting the g < 0 guard: atMost(-1) must be 0, otherwise the window logic breaks on the goal = 0 case.
  • Using prefix sums with a hash map: also correct and O(n) space, but the two-pass window is simpler and uses O(1) space.
  • Adding 1 instead of r - l + 1: every valid start position contributes a distinct subarray.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Sliding Window Problems

中文速览与面试要点

和相同的二元子数组

给你一个二元数组 nums,和一个整数 goal,请你统计并返回有多少个和为 goal 的 非空 子数组。子数组是数组的一段连续部分。约束:1 ≤ nums.length ≤ 3 × 10^4;nums[i] 为 0 或 1;0 ≤ goal ≤ nums.length。

核心要点

  • 方案一 · 前缀和 + 哈希表(与 560 题同构) :子数组 nums[j..i] 的和为 goal 等价于 prefix[i] − prefix[j−1] = goal ,即 prefix[j−1] = prefix[i] − goal 。用哈希表记录前缀和出现次数。
  • 方案二 · 「至多」作差(推荐,可处理负数场景) :定义 atMost(g) 为「和 ≤ g 的子数组个数」。由于 nums 只含 0/1(非负),滑动窗口可用,且 恰好 goal = atMost(goal) − atMost(goal − 1) 。
  • atMost 的滑动窗口 :右扩累加和,当 cur &gt; g 时收缩左边界。收缩结束后,以 r 结尾的合法子数组有 r − l + 1 个(左端点可取 l..r)。
  • 为什么 atMost 的累加是 r − l + 1 :窗口 [l, r] 是「以 r 结尾、和 ≤ g 的最大窗口」,因此所有以 r 结尾且左端点在 [l, r] 的子数组都合法。

常见陷阱

  • 漏掉 cnt[0] = 1 :会丢失所有「从下标 0 开始且和为 goal」的子数组。
  • 方案二中忘记 g &lt; 0 返回 0 : atMost(-1) 应为 0(任何子数组和都 ≥ 0),否则会得到负贡献。
  • 用滑动窗口直接求「恰好 goal」 :由于存在 0,窗口和不能唯一确定左边界位置,必须用「至多作差」或前缀和哈希。
  • 先 cnt[prefix] += 1 再 ans += cnt[prefix - goal] :顺序颠倒会多计。

参考实现

from collections import defaultdict

class Solution:
    def numSubarraysWithSum(self, nums: list[int], goal: int) -> int:
        # 方案一:前缀和 + 哈希表
        cnt = defaultdict(int)
        cnt[0] = 1
        prefix = 0
        ans = 0
        for x in nums:
            prefix += x
            ans += cnt[prefix - goal]
            cnt[prefix] += 1
        return ans

# 方案二:至多作差(滑动窗口)
# class Solution:
#     def numSubarraysWithSum(self, nums, goal):
#         def atMost(g):
#             if g < 0:
#                 return 0
#             l = cur = res = 0
#             for r, x in enumerate(nums):
#                 cur += x
#                 while cur > g:
#                     cur -= nums[l]; l += 1
#                 res += r - l + 1
#             return res
#         return atMost(goal) - atMost(goal - 1)