Given a binary string str, the task is to find the minimum number of operations required to make all the characters of the string same i.e. either the resultant string contains all 0s or all 1s. In a single operation, any block of consecutive 0s can be converted to a block of consecutive 1s of the same length and vice versa.
Input: str = “000111”
In a single operation, either change all 0s to 1s
or change all 1s to 0s.
Input: str = “0011101010”
All the 1s can be converted to 0s in 3 operations.
Approach: The problem is to convert all the characters into a single one. Now since converting a whole consecutive group of characters counts as a single step. You can calculate the number of different groups as separated by each other due to the presence of other characters in between them. Now the number of steps would be simply the minimum of both the numbers. Hence, the answer will be the minimum of the count of consecutive blocks of 0s or the count of consecutive blocks of 1s.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer Geeks Classes Live