Problem Description
Given an integer array, count the number of contiguous subarrays that are entirely filled with 0.
Key Insights
- A subarray is contiguous. For every sequence of consecutive 0's of length L, there are L * (L + 1) / 2 subarrays.
- Iterating through the array and counting consecutive zeros is an efficient approach.
- Once a non-zero element is encountered, compute the contributions from the current streak and then reset the count.
- Handle the edge case where the array ends with a sequence of zeros.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the array. Space Complexity: O(1), as only a few counter variables are used.
Solution
We use a simple linear scan with an integer counter to track consecutive zeros. Every time we see a zero, we increase the count. When a non-zero is encountered (or at the end of the array), we calculate the number of subarrays for that block using the formula L * (L + 1) / 2 and add it to our total. This way, we ensure all zero-filled subarrays are considered efficiently.