Minimum Number of Insertions in given String to Remove Adjacent Duplicates


In this problem, we will count the minimum number of characters we need to insert to remove all adjacent duplicate characters.

To solve the problem, we need to count the total number of adjacent duplicate character pairs.

Problem statement – We have given a string named str containing N alphabetical characters. We need to find the total number of different characters we require to add to the string such that the resultant string shouldn’t contain any adjacent duplicated characters.

Sample examples

Input

str = "ccddrt"

Output

2

Explanation – We need to insert one character between ‘cc’ and one character between ‘dd’.

Input

str = ‘abcdefrt’

Output

0

Explanation – The string doesn’t contain any adjacent duplicate characters. So, we don’t require to insert any character in the string.

Input

str = ‘ppppppp’

Output

6

Explanation – All characters of the string are same. So, we need to make string length – 1 insertion.

Approach 1

This approach will count the total number of adjacent duplicate characters in the string. The final count will be the answer, as we need to insert a new character between each adjacent duplicate character.

Algorithm

Step 1 – Initialize the str_size variable with the string size.

Step 2 – Also, declare and initialize the total_steps variable with 0 to store the minimum insertion into the string.

Step 3 – Start traversing the string using the for loop.

Step 4 – If the character at pth index is the same as (p – 1)th index, increase the total_Steps by 1.

Step 5 – At last, return the total_steps.

Example

#include <iostream>
using namespace std;

int totalInsertions(string alpha) {
    // srting lenght
    int str_size = alpha.size();
    // to store additions
    int total_steps = 0;
    // Iterate the string
    for (int p = 1; p < str_size; p++) {
        if (alpha[p] == alpha[p - 1])
            total_steps++;
    }
    // return count of additions
    return total_steps;
}
int main() {
    string str = "ccddrt";
    cout << "The total number of additions required to remove adjacent duplicates is - " << totalInsertions(str);
    return 0;
}

Output

The total number of additions required to remove adjacent duplicates is - 2

Time complexity – O(N) for iterating the string.

Space complexity – O(1) as we don’t use dynamic space.

The above problem is very similar to finding the total number of adjacent duplicate characters in the given string. Both problems have the same solution. Programmers can also try using the while loop to traverse the string and count the minimum number of insertions to remove all adjacent duplicates from the given string.

Updated on: 25-Aug-2023

44 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements