Skip to main content

2348. Number of Zero-Filled Subarrays

Problem Description​

Given an integer array nums, return the number of subarrays filled with 0.

A subarray is a contiguous non-empty sequence of elements within an array.

Examples​

Example 1:

Input: nums = [1,3,0,0,2,0,0,4]
Output: 6
Explanation:
There are 4 occurrences of [0] as a subarray.
There are 2 occurrences of [0,0] as a subarray.
There is no occurrence of a subarray with a size more than 2 filled with 0. Therefore, we return 6.

Example 2:

Input: nums = [0,0,0,2,0,0]
Output: 9
Explanation:
There are 5 occurrences of [0] as a subarray.
There are 3 occurrences of [0,0] as a subarray.
There is 1 occurrence of [0,0,0] as a subarray.
There is no occurrence of a subarray with a size more than 3 filled with 0. Therefore, we return 9.

Constraints​

  • 0 <= nums.length <= 10^5

Solution for 2348. Number of Zero-Filled Subarrays​

Implementation​

Live Editor
    function Solution(arr) {
  function zeroFilledSubarray(nums) {
    let ans = 0;
    let i = 0;
    while (i < nums.length) {
        if (nums[i] === 0) {
            let j = i;
            while (i < nums.length && nums[i] === 0) {
                ans += (i - j + 1);
                i++;
            }
        }
        i++;
    }
    return ans;
}

  const input = [1,3,0,0,2,0,0,4]
  const output =zeroFilledSubarray(input)
  return (
    <div>
      <p>
        <b>Input: </b>
        {JSON.stringify(input)}
      </p>
      <p>
        <b>Output:</b> {output.toString()}
      </p>
    </div>
  );
}
Result
Loading...

Complexity Analysis​

  • Time Complexity: O(n)O(n)
  • Space Complexity: O(1) O(1)

Code in Different Languages​

Written by @hiteshgahanolia
function zeroFilledSubarray(nums) {
let ans = 0;
let i = 0;
while (i < nums.length) {
if (nums[i] === 0) {
let j = i;
while (i < nums.length && nums[i] === 0) {
ans += (i - j + 1);
i++;
}
}
i++;
}
return ans;
}

References​