Open In App

Recursively remove all adjacent duplicates

Last Updated : 29 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given a string S, the task is to remove all its adjacent duplicate characters recursively.

Examples

Input: S = “geeksforgeek”
Output: “gksforgk”
Explanation: g(ee)ksforg(ee)k -> gksforgk

Input: S = “abccbccba”
Output: “
Explanation: ab(cc)b(cc)ba->abbba->a(bbb)a->aa->(aa)->”” (empty string)

[Naive Approach] Using Recursion – O(n ^ 2) Time and O(n ^ 2) Space

The idea is to first iteratively build a new string in result by removing adjacent duplicates. After one full pass, if the length of the string of result remains as original string, returns the result. If changes were made (meaning some duplicates were removed), simply calls itself recursively on the newly formed string. This ensures that any new adjacent duplicates formed by the removal of previous ones are also eliminated. The idea is to gradually “peel off” the duplicates layer by layer until no adjacent duplicates are left.

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Function to recursively remove adjacent duplicates
string rremove(string s) {
    // Create an empty string to build the result
    string sb = ""; 

    // Get the size of the input string
    int n = s.size(); 

    // Iterate over the length of current string
    for (int i = 0; i < n; i++) {
        bool repeated = false;

        // Check if the current characteris the same
        // as the next one
        while (i + 1 < n && s[i] == s[i + 1]) {
            repeated = true;  // Mark as repeated
          
            // Skip the next character
            // since it's a duplicate
            i++;  
        }

        // If the character was not repeated,
        // add it to the result string
        if (!repeated) sb += s[i];
    }

    // If no changes made, return the result string
    if (n == sb.length())
        return sb;
    
    // Otherwise, recursively call the function 
    // to check for more duplicates
    return rremove(sb);
}

int main() {
    string s = "geeksforgeek";  
    string result = rremove(s);  
    cout << result << endl;
    
    return 0;
}
C Java Python C# JavaScript

Output
gksforgk

Time Complexity: O(n2), In the worst case, the function may need to iterate almost through the entire string for each recursion, which makes the time complexity as O(N2).
Auxiliary Space: O(n2), as we are storing the new string in each recursive call and there can be n recursive call in the worst case.

[Expected Approach] Using Recursion – O(n2) Time and O(n) Space:

This solution also removes adjacent duplicates but it does this by modifying the string in place. It uses an index to track where to place non-duplicate characters. It skips over duplicate characters and moves only unique characters forward. After processing the original string, trims the original string to remove extra characters. If any adjacent duplicates were removed in this process then recursively call the function itself to repeat this process again. This approach is efficient because it modifies the string directly without creating new ones.

Below is the implementation of above approach.

C++
#include <bits/stdc++.h>
using namespace std;

// Helper function to remove adjacent duplicates
void remove_util(string &str, int n) {

     // Get the length of the string
    int len = str.length(); 

     // Index to store the result string
    int k = 0; 

    // Iterate over the string to remove adjacent
    // duplicates
    for (int i = 0; i < n; i++) {

        // Check if the current character is the same
        //  as the next one
        if (i < n - 1 && str[i] == str[i + 1]) {
            // Skip all the adjacent duplicates
            while (i < n - 1 && str[i] == str[i + 1]) {
                i++;
            }
        } else {
            // If not a duplicate, store the character
            str[k++] = str[i];
        }
    }

    // Remove the remaining characters from the
    // original string
    str.erase(k);

    // If any adjacent duplicates were removed,
    //  recursively check for more
    if (k != n)
        remove_util(str, k);
}

// Function to initiate the removal of adjacent
// duplicates
string rremove(string s) {

    // Call the helper function
    remove_util(s, s.length());

    // Return the modified string
    return s;  
}

int main() {
    string s = "geeksforgeek";
    cout << rremove(s) << endl; 
    return 0;
}
C Java Python C# JavaScript

Output
gksforgk

Time Complexity: O(n2), In the worst case, the function may need to iterate almost through the entire string for each recursion, which makes the time complexity as O(n2).
Auxiliary Space: O(n), considering the recursive call stack.



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg