2348. Number of Zero-Filled Subarrays
2348. Number of Zero-Filled Subarrays
1 | Given an integer array nums, return the number of subarrays filled with 0. |
Difficulty : Medium
Solution
The solution uses a simple iterative approach to count the number of subarrays filled with 0. We maintain two variables ans
and cur
. ans
stores the total count of subarrays filled with 0, and cur
stores the count of subarrays ending at the current index that are filled with 0.
We iterate through the given array nums and check if the current element is 0 or not. If the current element is 0, we increment cur
and add its value to ans. If the current element is not 0, we reset cur
to 0.
The reason we add cur
to ans
is that for every 0 in the array, there are cur subarrays that end at that index and are filled with 0. For example, if we have the input [1,3,0,0,2,0,0,4], the first 0 will be part of one subarray filled with 0, and the second 0 will be part of two subarrays filled with 0. Hence, we add the value of cur
to ans
.
Time Complexity
O(N)
Space Complexity
O(1)
1 | class Solution { |