3234. Count the Number of Substrings With Dominant Ones

3234. Count the Number of Substrings With Dominant Ones

Description

You are given a binary string s.

Return the number of substrings with dominant ones.

A string has dominant ones if the number of ones in the string is greater than or equal to the square of the number of zeros in the string.

Example 1:

1
2
3
Input: s = "00011"

Output: 5

Explanation:

The substrings with dominant ones are shown in the table below.

ijs[i..j]Number of ZerosNumber of Ones
33101
44101
230111
341102
2401112

Example 2:

1
2
3
Input: s = "101101"

Output: 16

Explanation:

The substrings with non-dominant ones are shown in the table below.

Since there are 21 substrings total and 5 of them have non-dominant ones, it follows that there are 16 substrings with dominant ones.

ijs[i..j]Number of ZerosNumber of Ones
11010
44010
14011022
041011023
150110123

Constraints:

  • 1 <= s.length <= 4 * 10^4
  • s consists only of characters '0' and '1'.

Hints/Notes

Solution

Language: C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution {
public:
int numberOfSubstrings(string s) {
vector<int> zeros;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '0') {
zeros.push_back(i);
}
}
int totalOne = s.size() - zeros.size();
int zeroIdx = 0, res = 0;
zeros.push_back(s.size());
// start from 0, we want to calculate the number of dominant substring
// with l as subString left index
for (int left = 0; left < s.size(); left++) {
// the meaning of the inner for loop:
// we calculate the number of zero and one up to jth zero(included)
// then we check the if the numZero and numOne fits the need
// if it fits, then all indexes starting from the jth zero,
// but before the (j+1)th zero works
// if it doesn't fit, then we need 1 from the next segment
for (int j = zeroIdx; j < zeros.size() - 1; j++) {
int numZero = j - zeroIdx + 1;
if (numZero * numZero > totalOne) {
break;
}
int numOne = zeros[j] + 1 - left - numZero;
int p = zeros[j], q = zeros[j + 1];
if (numZero * numZero <= numOne) {
res += q - p;
} else {
res += max(0, q - p + numOne - numZero * numZero);
}
}
if (s[left] == '0') {
zeroIdx++;
} else {
// from l to the left of first 0, all strings are valid
res += zeros[zeroIdx] - left;
totalOne--;
}
}
return res;
}
};