Skip to content

Commit 9cfeb4f

Browse files
authored
Create 2348-number-of-zero-filled-subarrays.java
1 parent 64bc6f2 commit 9cfeb4f

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
/**
2+
* 2348. Number of Zero-Filled Subarrays
3+
* Difficulty: Medium
4+
* URL: https://leetcode.com/problems/number-of-zero-filled-subarrays/description/
5+
*
6+
* ---------------------
7+
* Approach 1: Brute Force
8+
*
9+
* - Generate all possible subarrays using two loops.
10+
* - For each subarray, check if all elements are zero.
11+
* - If yes, increase the count.
12+
*
13+
* - In the given code, this is done by converting the subarray into a string
14+
* and checking if all characters are '0'.
15+
*
16+
* Time Complexity: O(n^3) → (O(n^2) subarrays × O(n) checking each)
17+
* Space Complexity: O(n) due to string building.
18+
*
19+
* Not practical for large inputs, but helps in understanding.
20+
*
21+
*/
22+
class Solution {
23+
public long zeroFilledSubarray(int[] nums) {
24+
int count = 0;
25+
for (int i = 0; i < nums.length; i++) {
26+
String str = "";
27+
for (int j = i; j < nums.length; j++) {
28+
str += nums[j] + "";
29+
boolean flag = true;
30+
for (int k = 0; k < str.length(); k++) {
31+
if (str.charAt(k) != '0') {
32+
flag = false;
33+
break;
34+
}
35+
}
36+
if (flag) {
37+
count++;
38+
}
39+
}
40+
}
41+
return count;
42+
}
43+
}
44+
45+
46+
/**
47+
* ---------------------
48+
* Approach 2: Optimized (Mathematical Counting)
49+
*
50+
* - Instead of generating all subarrays, notice:
51+
* For a streak of `k` consecutive zeros, number of zero-subarrays is:
52+
* k * (k + 1) / 2
53+
* (Formula of sum of first n natural numbers).
54+
*
55+
* Example: nums = [0,0,1,0]
56+
* - Streak1 = "00" → 2*(2+1)/2 = 3 subarrays → [0], [0], [0,0]
57+
* - Streak2 = "0" → 1*(1+1)/2 = 1 subarray → [0]
58+
* Total = 4
59+
*
60+
* Algorithm:
61+
* 1. Traverse array and keep track of consecutive zeros.
62+
* 2. When a non-zero is encountered, add contribution of that streak.
63+
* 3. After loop ends, add last streak if any.
64+
*
65+
* Time Complexity: O(n)
66+
* Space Complexity: O(1)
67+
*
68+
*/
69+
class Solution {
70+
public long zeroFilledSubarray(int[] nums) {
71+
long count = 0;
72+
long streak = 0;
73+
for (int i = 0; i < nums.length; i++) {
74+
if (nums[i] == 0) {
75+
streak++;
76+
} else {
77+
count += (streak * (streak + 1)) / 2;
78+
streak = 0;
79+
}
80+
}
81+
// Handle streak at the end
82+
if (streak > 0) {
83+
count += (streak * (streak + 1)) / 2;
84+
}
85+
return count;
86+
}
87+
}

0 commit comments

Comments
 (0)