NeetCode #136LC-2348MediumArrays & Hashing
← Back to All Problems#136 · #2348 · Number of Zero-Filled Subarrays(全 0 子数组的数目)
📌 Problem Statement & Constraints
Given an integer array
nums, return the number of subarrays filled with 0. Constraints: 1 <= nums.length <= 10^5, -10^9 <= nums[i] <= 10^9.💡 Core Algorithmic Approaches
- Every maximal run of
kconsecutive zeros contributesk * (k + 1) / 2zero-filled subarrays, since any contiguous slice of the run is valid. - So a single pass counting the current run length and accumulating it works: on a zero, increment the run and add the run length to the total.
- Adding the run length at each step is equivalent to the triangular number formula, but avoids a second pass.
- On a non-zero, reset the run to zero.
💻 Benchmark Python3 Implementation
class Solution:
def zeroFilledSubarray(self, nums: List[int]) -> int:
res = 0
run = 0
for x in nums:
if x == 0:
run += 1
res += run # run subarrays end here
else:
run = 0 # run broken
return res⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass.
💾 Space Complexity
O(1): two counters.
⚠️ Interview Pitfalls & Follow-ups
- Counting only maximal runs: you must count all subarrays within each run, which the incremental
res += rundoes. - Forgetting to reset the run: zeros separated by non-zeros would be merged into one run.
- Using the triangular formula after collecting all runs: correct but requires a second pass or extra bookkeeping.
- Confusing this with counting non-empty zero subarrays of any length: that is exactly what is being counted, so no adjustment is needed.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
全 0 子数组的数目
给你一个整数数组 nums,返回 全部由 0 组成 的子数组的数目。子数组是数组中的一个连续部分。约束:1 ≤ nums.length ≤ 10^5;-10^9 ≤ nums[i] ≤ 10^9。
核心要点
- 连续零段计数(标准解) :维护当前连续 0 的长度 run 。每遇到一个 0,以该位置 结尾 的全 0 子数组恰好有 run 个(起点可以是本段内的任意一个 0)。
- 累加规则 :遇到 0 则 run += 1 且 ans += run ;遇到非 0 则 run = 0 。
- 为什么 ans += run 是对的 :设当前零段长度为 L,则其中以当前位置结尾的子数组有 L 个(长度 1 到 L),因此每个位置贡献 run 个。
- 等价的组合公式 :对一个长度为 L 的极大零段,贡献为 L(L+1)/2 (即所有连续子段数)。两种写法等价。
常见陷阱
- 遇到 0 时只 run += 1 而不累加 ans :会漏掉子数组计数,最后只得到最长零段长度。
- 误以为答案是最长零段的长度 :题目问的是 子数组个数 ,不是长度。长度为 L 的零段贡献 L(L+1)/2 个子数组。
- 忘记遇到非 0 时重置 run :会导致零段跨越非零元素,计数错误。
- 用双重循环枚举所有子数组 :O(n²) 在 n = 10^5 时必然超时。
参考实现
class Solution:
def zeroFilledSubarray(self, nums: list[int]) -> int:
ans = 0
run = 0
for x in nums:
if x == 0:
run += 1
ans += run # 以当前位置结尾的全 0 子数组有 run 个
else:
run = 0
return ans
# 等价写法:对每个极大零段累加 L*(L+1)//2
# ans = run = 0
# for x in nums + [1]: # 末尾补一个非零,触发收尾
# if x == 0: run += 1
# else: ans += run * (run + 1) // 2; run = 0
# return ans