AlgoMaster Logo

Number of Zero-Filled Subarrays

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The simplest approach to solve this problem is to consider all possible subarrays and count those filled entirely with zeroes. While this method is straightforward, it can be inefficient for large arrays due to the sheer number of potential subarrays.

Steps:

  1. Iterate over all possible starting points of subarrays.
  2. For each starting point, extend the subarray endpoint till we are passing zeroes.
  3. Count the subarrays when a complete run of zeroes is detected.

Code:

2. Optimized Linear Scan

Intuition:

We can achieve a more optimal solution by recognizing runs of zeroes as we iterate over the array. For each segment of contiguous zeroes, the number of zero-filled subarrays can be calculated using combinatorial arithmetic.

Specifically, a contiguous run of k zeroes contributes k * (k + 1) / 2 zero-filled subarrays.

Steps:

  1. Initialize a counter for zero segments (zeroCount) and the total result (result).
  2. Traverse the array.
  3. For every zero encountered, increase the zeroCount.
  4. If a non-zero is encountered or the array ends, add the count of zero-filled subarrays for the segment, i.e., zeroCount * (zeroCount + 1) / 2 to the result, and reset zeroCount.
  5. Return the result.

Code:

Example Walkthrough:

0
0
1
0
2
1
3
0
4
0
5
0
6
2
zeroCount = 0, result = 0
Step 1 / 9