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
Number of Zero-Filled Subarrays INPUT nums = [1,3,0,0,2,0,0,4] 1 3 0 0 2 0 0 4 0 1 2 3 4 5 6 7 Zero Groups Identified: Group 1: indices [2,3] 2 consecutive zeros Group 2: indices [5,6] 2 consecutive zeros Find all subarrays of zeros in the input array ALGORITHM STEPS 1 Initialize Counters count = 0, result = 0 2 Iterate Array For each element in nums 3 Check Value If 0: count++, add to result Else: reset count = 0 4 Return Result Sum of all counts Math Formula: n consecutive zeros = n*(n+1)/2 subarrays Or: 1+2+3+...+n Group1: 1+2=3, Group2: 1+2=3 Total: 3+3 = 6 FINAL RESULT All Zero-Filled Subarrays: From Group 1 (indices 2-3): [0] at index 2 [0] at index 3 [0,0] indices 2-3 = 3 From Group 2 (indices 5-6): [0] at index 5 [0] at index 6 [0,0] indices 5-6 = 3 Output: 6 3 + 3 = 6 subarrays Key Insight: For n consecutive zeros, the number of zero-filled subarrays is n*(n+1)/2 (triangular number). Each new zero adds (count+1) new subarrays. Track consecutive zeros and sum contributions in O(n) time. TutorialsPoint - Number of Zero-Filled Subarrays | One Pass with Math Formula
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