Minimize insertions required to make all characters of a given string equal

• Last Updated : 29 Apr, 2021

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.

Examples:

Input: S = “11100”
Output: 1
Explanation:
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”
Output: 9

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:

C++14

 // C++ program for the above approach#include using namespace std; // Function to calculate the minimum// number of operations required to make// all characters of the string sameint minOperations(string& S){    // Stores count of operations    int count = 0;     // Traverse the string    for (int i = 1; i < S.length(); i++) {         // Check if adjacent        // characters are same or not        if (S[i] != S[i - 1]) {             // Increment count            count += 1;        }    }     // Print the count obtained    cout << count;} // Driver Codeint main(){    string S = "0101010101";    minOperations(S);     return 0;}

Java

 // Java program to implement// the above approachimport java.io.*;import java.util.*;class GFG{     // Function to calculate the minimum  // number of operations required to make  // all characters of the string same  static void minOperations(String S)  {     // Stores count of operations    int count = 0;     // Traverse the string    for (int i = 1; i < S.length(); i++)    {       // Check if adjacent      // characters are same or not      if (S.charAt(i) != S.charAt(i - 1))      {         // Increment count        count += 1;      }    }     // Print the count obtained     System.out.print(count);  }   // Driver Code  public static void main(String[] args)  {    String S = "0101010101";    minOperations(S);  }} // This code is contributed by susmitakundugoaldanga.

Python3

 # Python program to implement# the above approach # Function to calculate the minimum# number of operations required to make# all characters of the string samedef minOperations(S):     # Stores count of operations    count = 0;     # Traverse the string    for i in range(1, len(S)):         # Check if adjacent        # characters are same or not        if (S[i] != S[i - 1]):                       # Increment count            count += 1;     # Prthe count obtained    print(count); # Driver Codeif __name__ == '__main__':    S = "0101010101";    minOperations(S); # This code is contributed by 29AjayKumar

C#

 // C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{   // Function to calculate the minimum  // number of operations required to make  // all characters of the string same  static void minOperations(string S)  {     // Stores count of operations    int count = 0;     // Traverse the string    for (int i = 1; i < S.Length; i++)    {       // Check if adjacent      // characters are same or not      if (S[i] != S[i - 1])      {         // Increment count        count += 1;      }    }     // Print the count obtained    Console.Write(count);  }   // Driver Code  public static void Main()  {    string S = "0101010101";    minOperations(S);  }} // This code is contributed by code_hunt.

Javascript


Output:
9

Time Complexity: O(N)
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up