Minimum number of insertions in given String to remove adjacent duplicates
Given a string str of size N, the task is to find the minimum number of additions in the string such that no two consecutive elements are the same.
Examples:
Input: str=”rrg”
Output: 1
Explanation: Add an element between two r’sInput: str=”rrrrr”
Output: 4
Approach: The above problem can be solved using the above steps:
- Declare variable min_steps and initialise it by 0.
- Traverse the string using a for-loop from i=0 to i<N.
- Check if the current character is the same as the character before it.
- If yes, then increment min_steps by 1.
- Else, continue the loop.
- Print min_steps as the answer.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <iostream>using namespace std; // Function to find the minimum// number of additions such that// no two elements are the sameint minAdditions(string str){ // Storing length of the string int len = str.size(); // Variable to store // the number of steps needed int min_steps = 0; int i; // For loop to check // all colours in the string for (i = 1; i < len; i++) { if (str[i] == str[i - 1]) min_steps++; } // Returning the number of additions return min_steps;} // Driver Codeint main(){ string str = "RRG"; cout << minAdditions(str); return 0;} |
Output
1
Time Complexity: O(N)
Auxiliary Space: O(1)


.png)