2348. Number of Zero-Filled Subarrays #2072
-
Topics: Given an integer array A subarray is a contiguous non-empty sequence of elements within an array. Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to count the number of contiguous subarrays filled with zeros in a given integer array. The key insight here is recognizing that each segment of consecutive zeros contributes a certain number of zero-filled subarrays, which can be calculated using a mathematical formula. Approach
Let's implement this solution in PHP: 2348. Number of Zero-Filled Subarrays <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function zeroFilledSubarray($nums) {
$total = 0;
$currentCount = 0;
foreach ($nums as $num) {
if ($num == 0) {
$currentCount++;
} else {
$total += (int)($currentCount * ($currentCount + 1) / 2);
$currentCount = 0;
}
}
$total += (int)($currentCount * ($currentCount + 1) / 2);
return $total;
}
// Test cases
echo zeroFilledSubarray([1,3,0,0,2,0,0,4]) . "\n"; // 6
echo zeroFilledSubarray([0,0,0,2,0,0]) . "\n"; // 9
echo zeroFilledSubarray([2,10,2019]) . "\n"; // 0
?> Explanation:
This approach efficiently counts all zero-filled subarrays by leveraging contiguous segments of zeros and applying a mathematical formula to each segment, ensuring optimal performance even for large input sizes. |
Beta Was this translation helpful? Give feedback.
We need to count the number of contiguous subarrays filled with zeros in a given integer array. The key insight here is recognizing that each segment of consecutive zeros contributes a certain number of zero-filled subarrays, which can be calculated using a mathematical formula.
Approach
k
, the number of zero-filled subarrays within that segment is given by the formulak * (k + 1) / 2
. This is because each single zero forms a subarray of length 1, …