2914. Minimum Number of Changes to Make Binary String Beautiful #794
-
Topics: You are given a 0-indexed binary string A string is beautiful if it's possible to partition it into one or more substrings such that:
You can change any character in Return the minimum number of changes required to make the string Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to ensure that every pair of characters in the binary string Here's the step-by-step solution approach:
Let's implement this solution in PHP: 2914. Minimum Number of Changes to Make Binary String Beautiful <?php
/**
* @param String $s
* @return Integer
*/
function minChanges($s) {
$changes = 0;
$n = strlen($s);
for ($i = 0; $i < $n; $i += 2) {
// Check the current block of two characters
$first = $s[$i];
$second = $s[$i + 1];
if ($first !== $second) {
// If they are different, we need one change
$changes++;
}
// If they are the same, we do not need any changes
}
return $changes;
}
// Example usage
echo minChanges("1001"); // Output: 2
echo minChanges("10"); // Output: 1
echo minChanges("0000"); // Output: 0
?> Explanation:
Complexity:
This solution operates in O(n) time complexity, where n is the length of the string, making it efficient for the given constraints. |
Beta Was this translation helpful? Give feedback.
We need to ensure that every pair of characters in the binary string
s
is either"00"
or"11"
. If a pair is not in one of these two patterns, we will need to change one of the characters to make it match.Here's the step-by-step solution approach:
Divide the String into Blocks: Since a beautiful string can be formed from blocks of length 2, we can iterate through the string in steps of 2.
Count Changes: For each block of 2 characters, we need to determine the majority character (either
0
or1
). We will change the minority character in the block to match the majority character.Calculate Minimum Changes: For each block, if both characters are different, we will need 1 change; if they…