Skip to content

Commit e663b84

Browse files
authored
Create 3234-count-the-number-of-substrings-with-dominant-ones.js
1 parent d6de59f commit e663b84

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
* @param {string} s
3+
* @return {number}
4+
*/
5+
var numberOfSubstrings = function(s) {
6+
const n = s.length;
7+
let result = 0;
8+
9+
// Iterate through possible zero counts (1 to sqrt(n))
10+
for (let k = 1; k <= Math.floor(Math.sqrt(n)); k++) {
11+
const zeros = []; // Array to store positions of zeros
12+
let lastzero = -1; // Position of the zero before the first zero in our window
13+
let ones = 0; // Count of ones in our current window
14+
15+
// Scan through the string
16+
for (let right = 0; right < n; right++) {
17+
if (s[right] === '0') {
18+
zeros.push(right);
19+
// If we have more than k zeros, remove the leftmost one
20+
while (zeros.length > k) {
21+
ones -= (zeros[0] - lastzero - 1); // Subtract ones between lastzero and the removed zero
22+
lastzero = zeros.shift();
23+
}
24+
} else {
25+
ones++;
26+
}
27+
28+
// If we have exactly k zeros and at least k^2 ones
29+
if (zeros.length === k && ones >= k ** 2) {
30+
// Add the minimum of:
31+
// 1. Number of ways to extend to the left (zeros[0] - lastzero)
32+
// 2. Number of ways to extend to the right (ones - k^2 + 1)
33+
result += Math.min(zeros[0] - lastzero, ones - k ** 2 + 1);
34+
}
35+
}
36+
}
37+
38+
// Handle all-ones substrings
39+
let i = 0;
40+
while (i < n) {
41+
if (s[i] === '0') {
42+
i++;
43+
continue;
44+
}
45+
let sz = 0;
46+
while (i < n && s[i] === '1') {
47+
sz++;
48+
i++;
49+
}
50+
// Add number of all-ones substrings
51+
result += (sz * (sz + 1)) / 2;
52+
}
53+
54+
return result;
55+
};

0 commit comments

Comments
 (0)