Number of Zero-Filled Subarrays - Problem

Given an integer array nums, return the number of subarrays filled with 0.

A subarray is a contiguous non-empty sequence of elements within an array.

Input & Output

Example 1 — Mixed Array
$ Input: nums = [1,3,0,0,2,0,0,4]
Output: 6
💡 Note: Two segments of zeros: [0,0] contributes 3 subarrays, [0,0] contributes 3 subarrays. Total: 3+3=6
Example 2 — All Zeros
$ Input: nums = [0,0,0,0,0]
Output: 15
💡 Note: One segment of 5 zeros: 5×(5+1)/2 = 15 subarrays total
Example 3 — No Zeros
$ Input: nums = [2,10,2019]
Output: 0
💡 Note: No zeros in the array, so no zero-filled subarrays exist

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Zero-Filled Subarrays: Count All Zero-Only Contiguous SequencesInput: [1,3,0,0,2,0,0,4]13002004Segment 1Segment 22 zeros → 2×3/2 = 3 subarrays2 zeros → 2×3/2 = 3 subarraysTotal: 3 + 3 = 6 zero-filled subarraysSubarrays: [0], [0], [0,0] from first + [0], [0], [0,0] from secondOutput: 6
Understanding the Visualization
1
Input Array
Array with mixed zeros and non-zeros
2
Find Zero Segments
Identify consecutive zero groups
3
Count Subarrays
Apply formula n*(n+1)/2 per segment
Key Takeaway
🎯 Key Insight: For n consecutive zeros, there are exactly n×(n+1)/2 possible zero-filled subarrays
Asked in
Microsoft 15 Amazon 12
28.4K Views
Medium Frequency
~15 min Avg. Time
845 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