3234. Count the Number of Substrings With Dominant Ones #2423
-
|
Topics: You are given a binary string Return the number of substrings1 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:
Example 2:
Constraints:
Hint:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to count the number of substrings in a binary string where the number of ones is greater than or equal to the square of the number of zeros. The challenge is to efficiently compute this without checking every possible substring explicitly, which would be computationally expensive for large strings. Approach:
Let's implement this solution in PHP: 3234. Count the Number of Substrings With Dominant Ones <?php
/**
* @param String $s
* @return Integer
*/
function numberOfSubstrings($s) {
$n = strlen($s);
$pre0 = array_fill(0, $n + 1, 0);
$zeros = [];
for ($i = 0; $i < $n; $i++) {
$pre0[$i + 1] = $pre0[$i] + ($s[$i] == '0' ? 1 : 0);
if ($s[$i] == '0') {
$zeros[] = $i;
}
}
$totalZeros = count($zeros);
$count = 0;
for ($l = 0; $l < $n; $l++) {
$idx0 = $pre0[$l];
if ($idx0 < $totalZeros) {
$firstZero = $zeros[$idx0];
} else {
$firstZero = $n;
}
$count += ($firstZero - $l);
for ($k = 1; $k <= 200; $k++) {
if ($idx0 + $k - 1 >= $totalZeros) {
break;
}
$p = $zeros[$idx0 + $k - 1];
if ($idx0 + $k < $totalZeros) {
$q = $zeros[$idx0 + $k];
} else {
$q = $n;
}
$rMinValid = $l + $k * $k + $k - 1;
if ($rMinValid < $p) {
$startR = $p;
} else {
$startR = $rMinValid;
}
if ($startR < $q) {
$count += ($q - $startR);
}
}
}
return $count;
}
// Test cases
echo numberOfSubstrings("00011") . "\n"; // Output: 5
echo numberOfSubstrings("101101") . "\n"; // Output: 16
?>Explanation:
|
Beta Was this translation helpful? Give feedback.
We need to count the number of substrings in a binary string where the number of ones is greater than or equal to the square of the number of zeros. The challenge is to efficiently compute this without checking every possible substring explicitly, which would be computationally expensive for large strings.
Approach:
Problem Analysis: The problem requires checking all possible substrings of the given binary string to determine if they meet the condition where the number of ones is at least the square of the number of zeros. Directly checking all substrings would result in an O(n^2) solution, which is inefficient for large strings (n up to 40,000).
Key Insight: For any substring to sati…