Skip to content

2348. Number of Zero-Filled Subarrays 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  long long zeroFilledSubarray(vector<int>& nums) {
    long ans = 0;
    int indexBeforeZero = -1;

    for (int i = 0; i < nums.size(); ++i)
      if (nums[i])
        indexBeforeZero = i;
      else
        ans += i - indexBeforeZero;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public long zeroFilledSubarray(int[] nums) {
    long ans = 0;
    int indexBeforeZero = -1;

    for (int i = 0; i < nums.length; ++i)
      if (nums[i] == 0)
        ans += i - indexBeforeZero;
      else
        indexBeforeZero = i;

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def zeroFilledSubarray(self, nums: list[int]) -> int:
    ans = 0
    indexBeforeZero = -1

    for i, num in enumerate(nums):
      if num:
        indexBeforeZero = i
      else:
        ans += i - indexBeforeZero

    return ans