2348. Number of Zero-Filled Subarrays
MediumView on LeetCode
Time: O(n)
Space: O(1)
Advertisement
Intuition
Count subarrays with exactly 0 odd numbers. A subarray is zero-odd if all elements are even. Count maximal even subarrays.
Algorithm
- 1For each maximal even subarray of length L: subarrays = L*(L+1)/2.
Common Pitfalls
- •Split by odd numbers. Each even-only segment of length L contributes L*(L+1)/2 subarrays.
2348.cs
C#
// Approach: Track consecutive zero runs; each run of length k contributes k*(k+1)/2 subarrays.
// Time: O(n) Space: O(1)
public class Solution
{
public long ZeroFilledSubarray(int[] nums)
{
long totalCount = 0; // Initialize total count of zero-filled subarrays
int zeroCount = 0; // Initialize count of consecutive zeros
// Iterate through the array elements
foreach (int value in nums)
{
// Reset zeroCount to 0 if the current element is not zero
// Otherwise, increment zeroCount
zeroCount = (value != 0) ? 0 : zeroCount + 1;
// Add the current zeroCount to the total count
totalCount += zeroCount;
}
return totalCount; // Return the total count of zero-filled subarrays
}
}Advertisement
Was this solution helpful?