VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-number-of-replacements-to-make-the-binary-string-alternating-set-2/

⇱ Minimum number of replacements to make the binary string alternating | Set 2 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum number of replacements to make the binary string alternating | Set 2

Last Updated : 11 Jul, 2025

Given a binary string str, the task is to find the minimum number of characters in the string that have to be replaced in order to make the string alternating (i.e. of the form 01010101... or 10101010...).
Examples: 
 

Input: str = "1100" 
Output:
Replace 2nd character with '0' and 3rd character with '1'
Input: str = "1010" 
Output:
The string is already alternating. 
 


 


We have discussed one approach in Number of flips to make binary string alternate. In this post a better approach is discussed.
Approach: For the string str, there can be two possible solutions. Either the resultant string can be 
 

  1. 010101... or
  2. 101010...


In order to find the minimum replacements, count the number of replacements to convert the string in type 1 and store it in count then minimum replacement will be min(count, len - count) where len is the length of the string. len - count is the number of replacements to convert the string in type 2.
Below is the implementation of the above approach:
 


Output: 
2

 

Time Complexity: O(len), where len is the length of the given string. We are traversing till len.

Auxiliary Space: O(1), as we are not using any extra space.

Comment
Article Tags: