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
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
โ Linear Growth
Space Complexity
O(1)
Only using constant extra space for segment length tracking
โ Linear Space
Constraints
- 1 โค nums.length โค 105
- -109 โค nums[i] โค 109
- The answer will fit in a 64-bit integer
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code