#2348
Number of Zero-Filled Subarrays
MediumArrayMathArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of checking every subarray, we can count consecutive zeros and calculate the number of zero-filled subarrays that can be formed from them. This is efficient because it reduces the problem to a single pass through the array.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a count variable to zero and a consecutive zero counter to zero.
- 2Step 2: Traverse the array. For each zero encountered, increment the consecutive zero counter.
- 3Step 3: When a non-zero is encountered, add the count of subarrays formed by the consecutive zeros to the total count.
- 4Step 4: Reset the consecutive zero counter when a non-zero is found.
solution.py10 lines
1def zeroFilledSubarray(nums):
2 count = 0
3 consecutive_zeros = 0
4 for num in nums:
5 if num == 0:
6 consecutive_zeros += 1
7 count += consecutive_zeros
8 else:
9 consecutive_zeros = 0
10 return countℹ
Complexity note: This is linear time complexity because we only traverse the array once, making it much more efficient than the brute-force approach.
- 1Counting consecutive zeros allows us to calculate the number of zero-filled subarrays efficiently.
- 2Each group of consecutive zeros contributes to multiple subarrays, which can be summed up.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.