leetcode

Number of Zero-Filled Subarrays - Link

Question 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.


Constraints


Approach

Two approaches are provided:

Approach 1: Brute Force

Approach 2: Optimized (Mathematical Counting)

Why this approach works:

Alternative approaches considered:


Dry Run

Example Input: nums = [0, 0, 1, 0]

Approach 2 Dry Run:

Final Answer = 4


Solution

/**
 * ---------------------
 * Approach 1: Brute Force
 * ---------------------
 */
class SolutionBruteForce {
    public long zeroFilledSubarray(int[] nums) {
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            String str = "";
            for (int j = i; j < nums.length; j++) {
                str += nums[j] + "";
                boolean flag = true;
                for (int k = 0; k < str.length(); k++) {
                    if (str.charAt(k) != '0') {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    count++;
                }
            }
        }
        return count;
    }
}

/**
 * ---------------------
 * Approach 2: Optimized (Mathematical Counting)
 * ---------------------
 */
class Solution {
    public long zeroFilledSubarray(int[] nums) {
        long count = 0;
        long streak = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0) {
                streak++;
            } else {
                count += (streak * (streak + 1)) / 2;
                streak = 0;
            }
        }
        // Handle streak at the end
        if (streak > 0) {
            count += (streak * (streak + 1)) / 2;
        }
        return count;
    }
}

Time and Space Complexity