Recursively Remove All Adjacent Duplicates in Java



The problem statement states that we have given a String str of length N (where N is an integer) containing alphanumeric characters. We need to recursively remove all adjacent duplicate characters so that the resultant string does not contain any adjacent duplicate characters.

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

Example Scenario 1:

Input: str1 = "tuttor";
Output: res = tuor

The adjacent duplicate characters are tt which is removed from the string.

Example Scenario 2:

Input: str2 = "adbccbd";
Output: res = a

In the first step, it will remove cc from the string, and the string will become adbbd. After that, bb will be removed and the resultant string will be add. Next, remove dd, and the string will become a.

Example Scenario 3:

Input: str3 = "abcd";
Output: res = abcd

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

Using Recursion

In this approach, we will make recursive calls of function to remove adjacent string characters. Follow the steps below ?

  • 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 two characters are the same, the function removes all occurrences of that character from the beginning and calls itself recursively with the remaining string.

  • Step 3 ? If the first character is unique, it calls itself recursively on the substring starting from the second character.

  • Step 4 ? After the recursive call, function checks if the first character of original string matches the first character of the result from the recursive call. If they match, it removes the first character from the result.

  • Step 5 ? Otherwise, append the first character of the original string to the result from the recursive call.

Example

Here, we store the resultant string into temporary string after removing adjacent characters in the right part of the string.

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));
   }
}

On running the above code, it produce following result ?

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.

Using Iteration with Recursion

In this approach, iterate through the string to find adjacent duplicates characters and then calls the recursive function on the remaining part to remove those duplicate characters.

Example

Let's see a Java program that practically implement the above discussed approach.

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, ' '));
   }
}

When you run the above code, it will show the below result ?

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: 2024-08-16T08:06:38+05:30

673 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements