Java Program To Recursively Remove All Adjacent Duplicates
Last Updated :
17 Aug, 2023
Given a string, recursively remove adjacent duplicate characters from the string. The output string should not have any adjacent duplicates. See the following examples.
Examples:
Input: azxxzy
Output: ay
First "azxxzy" is reduced to "azzy".
The string "azzy" contains duplicates,
so it is further reduced to "ay".
Input: geeksforgeeg
Output: gksfor
First "geeksforgeeg" is reduced to
"gksforgg". The string "gksforgg"
contains duplicates, so it is further
reduced to "gksfor".
Input: caaabbbaacdddd
Output: Empty String
Input: acaaabbbacdddd
Output: acac
The following approach can be followed to remove duplicates in O(N) time:
- Start from the leftmost character and remove duplicates at left corner if there are any.
- The first character must be different from its adjacent now. Recur for string of length n-1 (string without first character).
- Let the string obtained after reducing right substring of length n-1 be rem_str. There are three possible cases
- If first character of rem_str matches with the first character of original string, remove the first character from rem_str.
- If remaining string becomes empty and last removed character is same as first character of original string. Return empty string.
- Else, append the first character of the original string at the beginning of rem_str.
- Return rem_str.
Below image is a dry run of the above approach:

Below is the implementation of the above approach:
Java
// Java program to remove all
// adjacent duplicatesfrom a string
import java.io.*;
import java.util.*;
class GFG
{
// Recursively removes adjacent
// duplicates from str and returns
// new string. las_removed is a
// pointer to last_removed character
static String removeUtil(String str,
char last_removed)
{
// If length of string is 1 or 0
if (str.length() == 0 ||
str.length() == 1)
return str;
// Remove leftmost same characters
// and recur for remaining
// string
if (str.charAt(0) == str.charAt(1))
{
last_removed = str.charAt(0);
while (str.length() > 1 &&
str.charAt(0) ==
str.charAt(1))
str = str.substring(1, str.length());
str = str.substring(1, str.length());
return removeUtil(str, last_removed);
}
// At this point, the first
// character is definiotely different
// from its adjacent. Ignore first
// character and recursively
// remove characters from remaining string
String rem_str = removeUtil(
str.substring(1, str.length()),
last_removed);
// Check if the first character of
// the rem_string matches with
// the first character of the original string
if (rem_str.length() != 0 &&
rem_str.charAt(0) == str.charAt(0))
{
last_removed = str.charAt(0);
// Remove first character
return rem_str.substring(
1, rem_str.length());
}
// If remaining string becomes
// empty and last removed character
// is same as first character of
// original string. This is needed
// for a string like "acbbcddc"
if (rem_str.length() == 0 &&
last_removed ==
str.charAt(0))
return rem_str;
// If the two first characters
// of str and rem_str don't match,
// append first character of str
// before the first character of
// rem_str
return (str.charAt(0) + rem_str);
}
static String remove(String str)
{
char last_removed = '';
return removeUtil(str, last_removed);
}
// Driver code
public static void main(String args[])
{
String str1 = "geeksforgeeg";
System.out.println(remove(str1));
String str2 = "azxxxzy";
System.out.println(remove(str2));
String str3 = "caaabbbaac";
System.out.println(remove(str3));
String str4 = "gghhg";
System.out.println(remove(str4));
String str5 = "aaaacddddcappp";
System.out.println(remove(str5));
String str6 = "aaaaaaaaaa";
System.out.println(remove(str6));
String str7 = "qpaaaaadaaaaadprq";
System.out.println(remove(str7));
String str8 = "acaaabbbacdddd";
System.out.println(remove(str8));
}
}
// This code is contributed by rachana soma
Output:
gksfor
ay
g
a
qrq
acac
a
Time Complexity: The time complexity of the solution can be written as T(n) = T(n-k) + O(k) where n is length of the input string and k is the number of first characters which are same. Solution of the recurrence is O(n).
Space complexity: O(n) for recursion stack, where n is the length of the string.
Thanks to Prachi Bodke for suggesting this problem and initial solution.
Another Approach:
The idea here is to check whether the String remStr has the repeated character that matches the last char of the parent String. If that is happening then we have to keep removing that character before concatenating string s and string remStr.
Below is the implementation of the above approach:
Java
// Java Program for above approach
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
// Recursively removes adjacent
// duplicates from str and
// returns new string. las_removed
// is a pointer to
// last_removed character
private static String removeDuplicates(
String s, char ch)
{
// If length of string is 1 or 0
if (s == null || s.length() <= 1)
{
return s;
}
int i = 0;
while (i < s.length())
{
if (i + 1 < s.length()
&& s.charAt(i) == s.charAt(i + 1))
{
int j = i;
while (j + 1 < s.length() &&
s.charAt(j) ==
s.charAt(j + 1))
{
j++;
}
char lastChar = i > 0 ? s.charAt(i - 1) : ch;
String remStr = removeDuplicates(
s.substring(j + 1, s.length()),
lastChar);
s = s.substring(0, i);
int k = s.length(), l = 0;
// Recursively remove all the adjacent
// characters formed by removing the
// adjacent characters
while (remStr.length() > 0 &&
s.length() > 0 &&
remStr.charAt(0) ==
s.charAt(s.length() - 1))
{
// Have to check whether this is the
// repeated character that matches the
// last char of the parent String
while (remStr.length() > 0 &&
remStr.charAt(0) != ch &&
remStr.charAt(0) ==
s.charAt(s.length() - 1))
{
remStr = remStr.substring(
1, remStr.length());
}
s = s.substring(0, s.length() - 1);
}
s = s + remStr;
i = j;
}
else
{
i++;
}
}
return s;
}
// Driver Code
public static void main(String[] args)
{
String str1 = "mississipie";
System.out.println(removeDuplicates(
str1, ' '));
String str2 = "ocvvcolop";
System.out.println(removeDuplicates(
str2, ' '));
}
}
// This code is contributed by Niharika Sahai
Output:
mpie
lop
Time Complexity: O(n)
Space Complexity: O(N),The recursion stack requires O(N) space. We are using additional space for the auxiliary string and the character variable.
Please refer complete article on Recursively remove all adjacent duplicates for more details!
Similar Reads
Java Program to Remove Duplicate Elements From the Array Given an array, the task is to remove the duplicate elements from an array. The simplest method to remove duplicates from an array is using a Set, which automatically eliminates duplicates. This method can be used even if the array is not sorted.Example:Java// Java Program to Remove Duplicate // Ele
6 min read
Java Program To Remove All The Duplicate Entries From The Collection As we know that the HashSet contains only unique elements, ie no duplicate entries are allowed, and since our aim is to remove the duplicate entries from the collection, so for removing all the duplicate entries from the collection, we will use HashSet.The HashSet class implements the Set interface,
3 min read
Java Program to Remove Duplicate Entries from an Array using TreeSet Features of TreeSet is the primary concern it is widely used in remove duplicates in the data structure as follows: TreeSet implements the SortedSet interface. So, duplicate values are not allowed and will be leftovers.Objects in a TreeSet are stored in a sorted and ascending order.TreeSet does not
3 min read
Java program to print all duplicate characters in a string Given a string, the task is to write Java program to print all the duplicate characters with their frequency Example: Input: str = "geeksforgeeks" Output: s : 2 e : 4 g : 2 k : 2 Input: str = "java" Output: a : 2 Approach: The idea is to do hashing using HashMap. Create a hashMap of type {char, int}
2 min read
How to Remove Duplicates from a String in Java? Working with strings is a typical activity in Java programming, and sometimes we need to remove duplicate characters from a string. In this article we have given a string, the task is to remove duplicates from it. Example Input: s = "geeks for geeks"Output: str = "geks for" Remove Duplicates From a
2 min read
Java Program For Removing Duplicates From An Unsorted Linked List Given an unsorted Linked List, the task is to remove duplicates from the list. Examples: Input: linked_list = 12 -> 11 -> 12 -> 21 -> 41 -> 43 -> 21 Output: 12 -> 11 -> 21 -> 41 -> 43 Explanation: Second occurrence of 12 and 21 are removed. Input: linked_list = 12 ->
6 min read
Java Program For Removing Duplicates From A Sorted Linked List Write a function that takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once. For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates() should convert the list to 11->21->43-
8 min read
How to Prevent the Addition of Duplicate Elements to the Java ArrayList? Ever wondered how you can make an ArrayList unique? Well, in this article we'll be seeing how to prevent the addition of duplicates into our ArrayList. If an ArrayList have three duplicate elements, but at the end, only the ones which are unique are taken into the ArrayList and the repetitions are n
3 min read
Java Program For Removing All Occurrences Of Duplicates From A Sorted Linked List Given a sorted linked list, delete all nodes that have duplicate numbers (all occurrences), leaving only numbers that appear once in the original list. Examples: Input: 23->28->28->35->49->49->53->53 Output: 23->35 Input: 11->11->11->11->75->75 Output: empty List Note that this is different from Rem
3 min read
How to Remove Duplicates from a String in Java Using Regex ? In Java programming, Regex (regular expressions) is a very important mechanism. It can be used to match patterns in strings. Regular expressions provide a short and simple syntax for describing the patterns of the text. In this article, we will be learning how to remove duplicates from a String in J
2 min read