714132. Number of Subarrays of 0's

Easy

Number of Subarrays of 0's

Slug: number-of-subarrays-of-0s--170647

Difficulty: Easy

Id: 714132

Topic Tags: Arrays

Company Tags: None

Summary

Given a binary array, we need to find the number of subarrays that contain only zeros.

The problem involves arrays and can be solved using a simple algorithmic approach. The key concept involved is counting the number of such subarrays.

Detailed Explanation

To solve this problem, we will iterate through the array and count the number of times we see a 0. When we see a 1, we reset our counter to 0. At the end of the array, the total count is the answer because each time we saw a 0, we were starting a new subarray that contains only zeros.

Here's a step-by-step breakdown:

  1. Initialize a variable count to 0.
  2. Iterate through the array from left to right.
  3. If you see a 0, increment count.
  4. If you see a 1, reset count to 0.
  5. After iterating through the entire array, return count.

This algorithm has a time complexity of O(n), where n is the size of the input array.

Time Complexity: O(n)

Space Complexity: O(1)

Optimized Solutions

Java

View on GeeksforGeeks
public int numSubarraysWithAllOnes(int[] arr) {
    int count = 0;
    for (int i : arr) {
        if (i == 0) {
            count++;
        } else {
            count = 0;
        }
    }
    return count;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.