2348. Number of Zero-Filled Subarrays
Problem 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.
Examples​
Example 1:
Input: nums = [1,3,0,0,2,0,0,4]
Output: 6
Explanation:
There are 4 occurrences of [0] as a subarray.
There are 2 occurrences of [0,0] as a subarray.
There is no occurrence of a subarray with a size more than 2 filled with 0. Therefore, we return 6.
Example 2:
Input: nums = [0,0,0,2,0,0]
Output: 9
Explanation:
There are 5 occurrences of [0] as a subarray.
There are 3 occurrences of [0,0] as a subarray.
There is 1 occurrence of [0,0,0] as a subarray.
There is no occurrence of a subarray with a size more than 3 filled with 0. Therefore, we return 9.
Constraints​
0 <= nums.length <= 10^5
Solution for 2348. Number of Zero-Filled Subarrays​
- Solution
Implementation​
Live Editor
function Solution(arr) { function zeroFilledSubarray(nums) { let ans = 0; let i = 0; while (i < nums.length) { if (nums[i] === 0) { let j = i; while (i < nums.length && nums[i] === 0) { ans += (i - j + 1); i++; } } i++; } return ans; } const input = [1,3,0,0,2,0,0,4] const output =zeroFilledSubarray(input) return ( <div> <p> <b>Input: </b> {JSON.stringify(input)} </p> <p> <b>Output:</b> {output.toString()} </p> </div> ); }
Result
Loading...
Complexity Analysis​
- Time Complexity:
- Space Complexity:
Code in Different Languages​
- JavaScript
- TypeScript
- Python
- Java
- C++
function zeroFilledSubarray(nums) {
let ans = 0;
let i = 0;
while (i < nums.length) {
if (nums[i] === 0) {
let j = i;
while (i < nums.length && nums[i] === 0) {
ans += (i - j + 1);
i++;
}
}
i++;
}
return ans;
}
function zeroFilledSubarray(nums: number[]): number {
let ans: number = 0;
let i: number = 0;
while (i < nums.length) {
if (nums[i] === 0) {
let j: number = i;
while (i < nums.length && nums[i] === 0) {
ans += (i - j + 1);
i++;
}
}
i++;
}
return ans;
}
class Solution:
def zeroFilledSubarray(self, nums: List[int]) -> int:
ans = 0
i = 0
while i < len(nums):
if nums[i] == 0:
j = i
while i < len(nums) and nums[i] == 0:
ans += (i - j + 1)
i += 1
i += 1
return ans
class Solution {
public long zeroFilledSubarray(int[] nums) {
long ans = 0;
int i = 0;
while (i < nums.length) {
if (nums[i] == 0) {
int j = i;
while (i < nums.length && nums[i] == 0) {
ans += (i - j + 1);
i++;
}
}
i++;
}
return ans;
}
}
class Solution {
public:
long long zeroFilledSubarray(vector<int>& nums) {
long long ans=0;
int i=0;
while(i<nums.size())
{
if(nums[i]==0)
{
int j=i;
while(i<nums.size() && nums[i]==0)
{
ans+= i-j+1;
i++;
}
}
i++;
}
return ans;
}
};
References​
-
LeetCode Problem: 2348. Number of Zero-Filled Subarrays
-
Solution Link: LeetCode Solution