Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

1758. Minimum Changes To Make Alternating Binary String

String

Explanation:

To make the string alternating, we need to ensure that no two adjacent characters are equal. We can iterate over the string and count the number of changes needed if we consider the string starting with '0' as the first character and the number of changes needed if we consider the string starting with '1' as the first character. The minimum of these two counts will be our answer.

  • Initialize two counters count0 and count1 to count the number of changes needed when considering the string starting with '0' and '1' respectively.
  • Iterate over the string and check if the current index is expected to be '0' or '1' based on the starting character.
  • Increment the respective counter if the character at the current index is not as expected.
  • Return the minimum of count0 and count1.

Time Complexity:

The time complexity of this solution is O(n), where n is the length of the input string.

Space Complexity:

The space complexity is O(1) since we are using only a constant amount of extra space.

:

class Solution {
    public int minOperations(String s) {
        int count0 = 0, count1 = 0;
        
        for (int i = 0; i < s.length(); i++) {
            if (i % 2 == 0) {
                if (s.charAt(i) != '0') count0++;
                if (s.charAt(i) != '1') count1++;
            } else {
                if (s.charAt(i) != '1') count0++;
                if (s.charAt(i) != '0') count1++;
            }
        }
        
        return Math.min(count0, count1);
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.