Java Program to Recursively Remove All Adjacent Duplicates


We need to remove all adjacent duplicate characters from the string in this problem. We can use a recursive or iterative approach to solve the problem. Here, we first need to remove the adjacent duplicate elements from the left part of the string. After that, we need to recursively remove the adjacent duplicates from the right part of the string.

Problem statement − We have given string str of length N containing alphanumeric characters. We need to recursively remove all adjacent duplicate characters so that the resultant string does not contain any adjacent duplicate characters.

Sample examples

Input

str1 = "tuttor"

Output

tuor

Explanation − We removed the adjacent ‘tt’ from the string.

Input

 str1 = "adbccbd"

Output

a

Explanation

  • In the first step, it will remove ‘cc’ from the string, and the string will be ‘adbbd’

  • After that, we need to remove ‘bb’ from the string, and the resultant string will be ‘add’.

  • Next, we need to remove ‘dd’, and the string will be ‘a’.

Input

 str1 = ‘abcd’

Output

‘abcd’

Explanation − The string doesn’t contain any adjacent duplicates. So, the output string is the same as the input string.

Approach 1

In this approach, we will make recursive calls of function to remove adjacent string characters.

Algorithm

Step 1 − If the string length is 0 or 1, return the same string as it doesn’t contain any duplicates.

Step 2 − If the first character is the same as the second character, assign the first character of the string to the ‘last_char’ variable, as we need to remove the first character from the string.

Step 3 − Use the loop, and remove all the same characters from the start of the string.

Step 4 − Recursively call the function to remove the adjacent characters from the string.

Step 5 − After that, the first character will be unique. So, call the recursivelyRemove() function for the string starting from the 1st index and store returned value in the temp variable.

Step 6 − If the first character of the ‘temp’ string is the first character of the ‘alpha’ string, remove the first character from the temp string and return it.

Step 7 − If the temp string is empty, and the value of the ‘last_char’ variable is equal to the first character of the ‘alpha’ string, return the ‘temp’ string.

Step 8 − Return the resultant string after concatenating the first character of the alpha string and full temp string.

Example

Here, in the ‘temp’ string, we get the resultant string after removing adjacent characters in the right part of the string. It may be possible the first character of the ‘temp’ string and the first character of the alpha string can be the same. As we need to concat the first character of the alpha and temp string, we need to remove the first character from the temp string if we get adjacent elements.

import java.io.*;
import java.util.*;

public class Main {
    static String recursivelyRemove(String alpha, char last_char) {
        // base case
        if (alpha.length() == 0 || alpha.length() == 1)
            return alpha;
        // Remove duplicate characters from the left, and then recursively call for the
        // right part
        if (alpha.charAt(0) == alpha.charAt(1)) {
            last_char = alpha.charAt(0);
            while (alpha.length() > 1 && alpha.charAt(0) == alpha.charAt(1))
                alpha = alpha.substring(1, alpha.length());
            alpha = alpha.substring(1, alpha.length());
            return recursivelyRemove(alpha, last_char);
        }
        // First character will be unique, so remove duplicates from another part
        String temp = recursivelyRemove(alpha.substring(1, alpha.length()), last_char);
        // If the first character is the same as the first character of the original string, remove it.
        if (temp.length() != 0 && temp.charAt(0) == alpha.charAt(0)) {
            last_char = alpha.charAt(0);
            return temp.substring(1, temp.length());
        }
        // If the temp string is empty, and last_char is equal to the first character of the original, return temp.
        if (temp.length() == 0 && last_char == alpha.charAt(0))
            return temp;
        // append first character with temp and return.
        return (alpha.charAt(0) + temp);
    }
static String duplicateRemoval(String str) {
	return recursivelyRemove(str, '\0');	
}
    public static void main(String args[]) {
        String str1 = "tuttor";
        System.out.println("The string after recursively removing the adjacent duplicates is - " + duplicateRemoval(str1));
    }
}

Output

The string after recursively removing the adjacent duplicates is - tuor

Time complexity− T(N) = T(N−K) + O(K) ~ O(N*K) as we remove the first same characters from the string.

Space complexity − O(N) to store the string in the temp string.

Approach 2

We will use the loops to remove duplicate elements in this approach iteratively. However, we will also call a recursive function to remove duplicated adjacent elements from different string parts.

Algorithm

Step 1 − Return the string itself if the string is null or the length is euqla to 1.

Step 2 − Initialize the ‘p’ variable with 0, and make iterations until ‘p’ is less than the string length.

Step 3 − Next, we need to remove the same characters from the start of the string using the nested loop. Also, update the ‘last_removed’ variable.

Step 4 − Now, call the duplicateRemoval() function again to remove the duplicated adjacent elements from the remaining string. Also, store the returned value in the ‘tempStr’ string.

Step 5 − Get the substring of length p from alpha, as it doesn’t contain any adjacent duplicate elements.

Step 6 − Now, we need to remove the starting characters of the ‘tempStr’ string if they are the same because we need to concat the alpha and ‘tempStr’ strings.

Step 7 − Also, remove the last character from the alpha string if it is matching with the first character of the ‘tempStr’ string.

Step 8 − Merge the alpha with tempStr, and update the value of the p by assigning q.

Step 9 − At the end, return the alpha string.

Example

import java.io.*;
import java.util.*;

public class Main {
    static String duplicateRemoval(String alpha, char ch) {
        // base case
        if (alpha == null || alpha.length() <= 1) {
            return alpha;
        }
        int p = 0;
        while (p < alpha.length()) {
            // If characters at index p and q are the same
            if (p + 1 < alpha.length() && alpha.charAt(p) == alpha.charAt(p + 1)) {
                // Finding first q same characters
                int q = p;
                while (q + 1 < alpha.length() && alpha.charAt(q) == alpha.charAt(q + 1)) {
                    q++;
                }
                // store the last removed character
                char last_removed = p > 0 ? alpha.charAt(p - 1) : ch;
                // Remove duplicate from remaining part
                String tempStr = duplicateRemoval(alpha.substring(q + 1, alpha.length()), last_removed);
                alpha = alpha.substring(0, p);
                int len = alpha.length(), l = 0;
                // If the last char of the alpha string and the first char of tempStr are the same, remove them until they match
                while (tempStr.length() > 0 && alpha.length() > 0
                        && tempStr.charAt(0) == alpha.charAt(alpha.length() - 1)) {
                    // Make iterations until tempStr has the first character the same as the last character of
                    while (tempStr.length() > 0 && tempStr.charAt(0) != ch
                            && tempStr.charAt(0) == alpha.charAt(alpha.length() - 1)) {
                        tempStr = tempStr.substring(1, tempStr.length());
                    }
                    // remove last character from alpha
                    alpha = alpha.substring(0, alpha.length() - 1);
                }               
                alpha = alpha + tempStr; // append alpha to tempStr
                p = q; // updating p-value
            } else {
                p++;
            }
        }
        return alpha;
    }
    public static void main(String args[]) {
        String str1 = "tuttorppoi";
        System.out.println(
                "The string after recursively removing the adjacent duplicates is - " + duplicateRemoval(str1, ' '));
    }
}

Output

The string after recursively removing the adjacent duplicates is - tuoroi

Time complexity− O(N) as we traverse the string.

Space complexity − O(N) as we store the temporary string.

Updated on: 14-Aug-2023

263 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements