Minimum Number of Changes to Make Binary String Beautiful

Updated on 17 June, 2025
Minimum Number of Changes to Make Binary String Beautiful header image

Problem Statement

In this task, you are provided with a binary string s of even length. You need to transform this string into a "beautiful" string. The criteria for a string to be considered beautiful is that it can be divided into one or more substrings where each substring:

  • Has an even length
  • Consists solely of either all '1's or all '0's.

You may change any character in the string s to either '0' or '1' to achieve this goal. The objective is to determine the minimum number of changes required to convert the given string into a beautiful string. This involves strategically flipping some bits in the string to minimize the effort while ensuring that the resultant string meets the criteria for being beautiful.

Examples

Example 1

Input:

s = "1001"

Output:

2

Explanation:

We change s[1] to 1 and s[3] to 0 to get string "1100".
It can be seen that the string "1100" is beautiful because we can partition it into "11|00".
It can be proven that 2 is the minimum number of changes needed to make the string beautiful.

Example 2

Input:

s = "10"

Output:

1

Explanation:

We change s[1] to 1 to get string "11".
It can be seen that the string "11" is beautiful because we can partition it into "11".
It can be proven that 1 is the minimum number of changes needed to make the string beautiful.

Example 3

Input:

s = "0000"

Output:

0

Explanation:

We don't need to make any changes as the string "0000" is beautiful already.

Constraints

  • 2 <= s.length <= 105
  • s has an even length.
  • s[i] is either '0' or '1'.

Approach and Intuition

The central idea to solve this problem lies in pairing consecutive characters. Since each desired substring must have an even length, you can start by considering pairs of characters:

  1. Traverse the string two characters at a time since we need even-length substrings:
  2. For each pair, check if both characters are the same. If they are, this pair is already uniform and can be part of a beautiful string without any changes.
  3. If the characters in the pair are different, one change is necessary to make them the same:
    • You can either change the first character to match the second or vice versa.
    • Alternatively, decide based on a pattern or rule you might establish (like always preferring '0' over '1' or vice versa) but typically, the choice doesn't affect the count in an isolated pair.

Given the simplicity of pairs, the total minimum number of changes required will be the count of mismatched pairs, i.e., pairs where the two characters are different.

Considering this approach, let’s analyze the given examples:

  • For s = "1001", the pairs are ("10", "01"):
    • Both pairs are mismatched, requiring one change each. You change the second character in the first pair and the second character in the second pair to get "1100", which is evenly splittable into "11" and "00".
  • For s = "10", the pair itself is mismatched. Changing either character will yield a uniform pair like "11" or "00".
  • For s = "0000", all possible groupings ("00", "00") are uniform, so no changes are needed.

Thus, the algorithm focuses primarily on counting and modifying mismatched pairs to minimize modifications to achieve a beautiful string.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    int minimumEditSteps(string str) {
        int editsNeeded = 0;

        for (int idx = 0; idx < str.length() - 1; idx += 2) {
            if (str[idx] != str[idx + 1]) {
                editsNeeded++;
            }
        }

        return editsNeeded;
    }
};

This C++ solution finds the minimum number of changes needed to make a binary string beautiful. A binary string is considered beautiful if every pair of consecutive characters contains distinct characters. The solution involves iterating through the binary string in steps of 2 using a loop. For each character pair, if the current and the next character are the same, an increment to the counter editsNeeded is done to indicate a necessary edit. The function returns the total count of such required changes to achieve a beautiful string.

  • The function minimumEditSteps takes a string str as its argument.
  • A variable editsNeeded initializes to zero to count the necessary edits.
  • A for-loop runs through the string checking every two consecutive characters.
  • If the characters are identical, the counter editsNeeded is incremented.
  • Ultimately, the function returns the value of editsNeeded that represents the minimum number of edits required.
java
class Solution {

    public int minimumEdits(String str) {
        int editsNeeded = 0;

        for (int idx = 0; idx < str.length(); idx += 2) {
            if (str.charAt(idx) != str.charAt(idx + 1)) {
                editsNeeded++;
            }
        }

        return editsNeeded;
    }
}

The problem requires calculating the minimum number of changes to make a binary string beautiful; a binary string is termed "beautiful" if no two consecutive characters in the string are the same. The Java solution provided involves a method named minimumEdits, which processes the string to determine how many edits are necessary.

The code operates as follows:

  1. Initialize an editsNeeded counter to track the number of changes.
  2. Loop through the characters in the binary string. The loop increments by two, checking pairs of adjacent characters.
  3. For each character pair, if the two characters are the same, increment the editsNeeded counter by one.
  4. Return the value of editsNeeded.

This method effectively counts the number of adjacent similar characters in pairs, incrementing the counter each time a pair of identical characters is found. This count gives the minimum edits needed to ensure no two consecutive characters are the same, ensuring the binary string becomes "beautiful."

The logic executes in O(n/2) time complexity where n is the length of the string, since it examines the string in steps of two. This makes the method efficient, especially for large strings, by minimizing the number of iterations needed.

python
class Solution:
    def minimumAdjustments(self, s: str) -> int:
        required_changes = 0
        for idx in range(0, len(s), 2):
            if s[idx] != s[idx + 1]:
                required_changes += 1
        return required_changes

The Python solution provided addresses the problem of converting a binary string into a beautiful string where each pair of adjacent characters are the same. The solution uses a straightforward approach to count the minimum number of swaps required:

  • Initialize a counter required_changes to zero.
  • Iterate over the characters in the string in steps of 2.
  • For each pair, compare the characters. If they are not the same, increase the required_changes counter by one.
  • Return the required_changes value, which indicates the minimum adjustments needed.

This method ensures that the string is examined efficiently, by only checking pairs rather than every single character, leading to an optimal solution for the given problem.

Comments

No comments yet.