Number of Zero-Filled Subarrays

medium array math

Problem

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.

Inputnums = [1, 3, 0, 0, 2, 0, 0, 4]
Output6
Two zero runs of length 2 each. Each contributes 2·3/2 = 3 subarrays. Total = 6.

def zero_filled_subarray(nums):
    total = 0
    run = 0
    for x in nums:
        if x == 0:
            run += 1
            total += run
        else:
            run = 0
    return total
function zeroFilledSubarray(nums) {
  let total = 0;
  let run = 0;
  for (const x of nums) {
    if (x === 0) {
      run += 1;
      total += run;
    } else {
      run = 0;
    }
  }
  return total;
}
class Solution {
    public long zeroFilledSubarray(int[] nums) {
        long total = 0;
        long run = 0;
        for (int x : nums) {
            if (x == 0) {
                run += 1;
                total += run;
            } else {
                run = 0;
            }
        }
        return total;
    }
}
long long zeroFilledSubarray(vector<int>& nums) {
    long long total = 0;
    long long run = 0;
    for (int x : nums) {
        if (x == 0) {
            run += 1;
            total += run;
        } else {
            run = 0;
        }
    }
    return total;
}
Time: O(n) Space: O(1)