Minimize insertions required to make all characters of a given string equal
Given a binary string S of length N, the task is to find the minimum number of characters required to be inserted such that all the characters in the string becomes the same based on the condition that:
If ‘1’ is inserted into the string, then all the ‘0’s nearest to the inserted ‘1’ is flipped or vice-versa.
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.
Input: S = “11100”
Operation 1: Inserting ‘1’ at the last of the given string modifies S to “111001”. Adding ‘1’ to the last flips all the nearest ‘0’s to the inserted ‘1’. Therefore, the resultant string is “111111”.
After completing the above operation, all the characters of the string are the same. Therefore count of operations is 1.
Input: S = “0101010101”
Approach: The idea is to solve this problem by Greedy Approach based on the following observations:
- It can be seen that inverting one continuous section of ‘1’s or ‘0’s reduces the number of sections by one in this operation. Therefore, it is sufficient to repeat this operation to make it all into one section. The number of operations required is equal to sections – 1.
- In simpler terms, count the total number of non-equal adjacent pair of characters, so that inverting one of them can convert the whole substring into similar substrings.
Follow the steps below to solve the problem:
- Initialize a variable, say count, that stores the count of different adjacent characters.
- Traverse the string and check if the current and the next characters are different, then increment the value of count.
- After completing the above steps, print the value of count as the minimum required operations.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)