Number of Zero-Filled Subarrays (LeetCode 2348): Solution and Explanation

Medium
Array
Math

Given an integer array nums, count the contiguous subarrays whose elements are all 0.

Intuition

Listing every subarray and checking it is O(n^2) or worse. The trick is to count each zero-filled subarray exactly once, at its right end.

Suppose index i holds a 0 and the streak of zeros ending at i has length run. A zero-filled subarray ending at i must start somewhere inside that streak, and every start in the streak works. So exactly run new subarrays end at i.

Scan left to right, extend run on each 0, reset it on anything else, and add run to the total at every 0. A streak of length L adds 1 + 2 + ... + L = L(L+1)/2, which is the number of subarrays inside it.

Approach: Running streak length

  1. Set total = 0 and run = 0.
  2. For each value x in nums: if x == 0, increase run by 1 and add run to total.
  3. Otherwise set run = 0, because no zero-filled subarray can cross a nonzero value.
  4. Return total.

Step-by-step example

nums = [1,3,0,0,2,0,0,4]
  1. Indices 0 and 1 hold 1 and 3, so run stays 0.
  2. Index 2 is 0: run = 1, total = 1 (the subarray [0] at index 2).
  3. Index 3 is 0: run = 2, total = 3 ([0] at index 3 and [0,0] from 2 to 3).
  4. Index 4 is 2: run resets to 0.
  5. Indices 5 and 6 are 0: run goes 1 then 2, so total goes 4 then 6.
  6. Index 7 is 4: run resets. Return 6.

Code: Python, Java, C++

1class Solution:
2    def zeroFilledSubarray(self, nums: List[int]) -> int:
3        total = 0
4        run = 0
5        for x in nums:
6            if x == 0:
7                run += 1
8                total += run
9            else:
10                run = 0
11        return total
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass over the array with constant work per element.

Space

O(1)

Only total and run are stored.

Other approaches

Sum L(L+1)/2 per streak (time O(n), space O(1))

Find each maximal streak of zeros, measure its length L, and add L(L+1)/2. It is the same count grouped by streak instead of by right end.

Check every subarray (time O(n^2), space O(1))

For every start index, extend to the right while the values are 0 and count each step. Simple, but quadratic on an array of all zeros.

Common mistakes

  • Overflow. On LeetCode an array of 10^5 zeros gives about 5 * 10^9 subarrays, so the total must be a 64-bit long there. This page's judge uses an int return, and its tests keep the answer within 32 bits.
  • Adding 1 per zero instead of run. That counts single-element subarrays only.
  • Forgetting to reset run at a nonzero value, which glues two separate streaks together.

Frequently asked questions

Why does a zero at the end of a streak of length run add exactly run subarrays?

A zero-filled subarray ending there can start at any of the run zeros in the streak, and starting any earlier would include a nonzero value.

Do negative numbers change anything?

No. Only whether a value equals 0 matters. Any nonzero value, positive or negative, ends the streak.

Why is the return type int here when LeetCode uses long?

The judge on this site has no 64-bit return type, so tests are sized so the answer fits in an int. On LeetCode, use long (or long long) for the total.