Number of Zero-Filled Subarrays

MediumArrays · Counting Runs🧩 Array ManipulationLeetCode #2348 ↗Updated

Problem

Given an integer array nums, count how many contiguous, non-empty subarrays consist only of zeros. Subarrays at different positions count separately even if they look the same. The answer can exceed the int range, so return a long.
Inputnums = [1,3,0,0,2,0,0,4]Output6 (four [0] + two [0,0])
Inputnums = [0,0,0,2,0,0]Output9 (run of 3 gives 6, run of 2 gives 3)
Inputnums = [2,10,2019]Output0

1 ≤ n ≤ 105  ·  -109 ≤ nums[i] ≤ 109

Try it yourself

Java
class Solution {
    public long zeroFilledSubarray(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Count subarrays by their right end: if the current zero streak has length len, exactly len all-zero subarrays end here. Summing the streak at every index gives the answer in one pass.
PatternArray Manipulation

Instinct "In place", "O(1) extra space" or "one pass" over an array? Think write pointer, reversal, prefix/suffix passes or using indices as storage.

Memory hack Read fast, write slow, reverse to rotate, and let the index be the hash.

Open the Array Manipulation guide →

Approaches

Brute ForceEnumerate and Verify Every Subarray

Time O(n3)Space O(1)

List every pair (i, j) and scan nums[i..j] to see whether all entries are zero. It is the definition turned into code.

Java
public long zeroFilledSubarray(int[] nums) {
    int n = nums.length;
    long count = 0;
    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
            boolean allZero = true;
            for (int k = i; k <= j && allZero; k++) {
                if (nums[k] != 0) allZero = false;
            }
            if (allZero) count++;
        }
    }
    return count;
}

Directly mirrors the statement, but cubic time is far too slow.

At a glance

LevelApproachTimeSpace
Brute ForceEnumerate and Verify Every SubarrayO(n3)O(1)
BetterExtend from Each Start, Stop at a Non-ZeroO(n2)O(1)
OptimalOne Pass — Add the Current StreakO(n)O(1)
Common pitfalls
  • Returning int — 105 zeros give ~5·109 subarrays, which overflows.
  • Counting only maximal runs (one per block) instead of every sub-run inside each block.
  • Forgetting to reset the streak on a non-zero, which merges separate blocks.
Interview tips
  • Do a tiny example by hand: a run of 3 zeros → 3 + 2 + 1 = 6 subarrays.
  • Explain the “count by right end” view; it avoids any formula derivation.
  • Call out the long return type before the interviewer does.
Pattern
Count by right endpoint / run length → number of subarrays where every element meets a condition.
My notes saved in this browser