Number of Zero-Filled Subarrays - Problem

Given an integer array nums, your task is to count the total number of subarrays that contain only zeros.

A subarray is a contiguous sequence of elements within an array that maintains the original order. For example, in the array [1, 0, 0, 2], some subarrays include [1], [0, 0], [1, 0, 0, 2], etc.

Goal: Count all possible subarrays where every element is zero.

Example: In [1, 0, 0, 0, 2], the zero-filled subarrays are: [0] (3 times), [0, 0] (2 times), and [0, 0, 0] (1 time), totaling 6 subarrays.

Input & Output

example_1.py โ€” Basic Case
$ Input: [1,3,0,0,2,0,0,4]
โ€บ Output: 6
๐Ÿ’ก Note: There are 4 occurrences of [0] as a subarray. There are 2 occurrences of [0,0] as a subarray. There is no occurrence of a subarray with a size more than 2 filled with 0. Therefore, we return 6.
example_2.py โ€” All Zeros
$ Input: [0,0,0,2,0,0]
โ€บ Output: 9
๐Ÿ’ก Note: First segment [0,0,0]: 3*(3+1)/2 = 6 subarrays. Second segment [0,0]: 2*(2+1)/2 = 3 subarrays. Total: 6 + 3 = 9.
example_3.py โ€” No Zeros
$ Input: [2,10,2019]
โ€บ Output: 0
๐Ÿ’ก Note: There are no subarrays filled with 0, so we return 0.

Visualization

Tap to expand
Zero-Filled Subarrays: Mathematical InsightInput Array:100200Segment 1: Length 200โ†’ 2ร—3/2 = 3 subarraysSegment 2: Length 200โ†’ 2ร—3/2 = 3 subarraysMathematical FormulaFor n consecutive zeros: n ร— (n + 1) / 2 subarraysโ€ข Segment 1 (length 2): 2 ร— 3 / 2 = 3โ€ข Segment 2 (length 2): 2 ร— 3 / 2 = 3Total: 3 + 3 = 6 zero-filled subarrays
Understanding the Visualization
1
Identify Segments
Scan array to find consecutive zero groups
2
Apply Formula
For each segment of length n, calculate n*(n+1)/2
3
Sum Results
Add up contributions from all segments
Key Takeaway
๐ŸŽฏ Key Insight: Use nร—(n+1)/2 formula to count subarrays in each consecutive zero segment, avoiding the need to enumerate every possible subarray individually.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through the array, each element visited once

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using constant extra space for segment length tracking

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • -109 โ‰ค nums[i] โ‰ค 109
  • The answer will fit in a 64-bit integer
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
23.8K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen