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:
- Initialize a variable
countto 0. - Iterate through the array from left to right.
- If you see a 0, increment
count. - If you see a 1, reset
countto 0. - 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
public int numSubarraysWithAllOnes(int[] arr) {
int count = 0;
for (int i : arr) {
if (i == 0) {
count++;
} else {
count = 0;
}
}
return count;
}