Recursively remove all adjacent duplicates
Last Updated :
23 Jul, 2025
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
#include <stdio.h>
#include <string.h>
// Function to recursively remove adjacent
// duplicates
void rremove(char *s){
// Get the size of the input string
int n = strlen(s);
// Initialize result string
char sb[101] = "";
int k = 0;
// Iterate over the length of current string
for (int i = 0; i < n; i++){
// Flag to check if the current character
// is repeated
int repeated = 0;
// Check if the current character is the
// same as the next one
while (i + 1 < n && s[i] == s[i + 1]){
// Mark as repeated
repeated = 1;
// 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[k++] = s[i];
}
// If no changes made, return the result string
sb[k] = '\0';
if (n == k)
strcpy(s, sb);
else{
// Otherwise, recursively call function
// to check for more duplicates
strcpy(s, sb);
rremove(s);
}
}
int main(){
char s[] = "geeksforgeek";
rremove(s);
printf("%s", s);
return 0;
}
Java
class GfG {
// Function to recursively remove adjacent duplicates
static String rremove(String s)
{
// Create an empty string to build the result
StringBuilder sb = new StringBuilder();
// Get the size of the input string
int n = s.length();
// Iterate over the length of current string
for (int i = 0; i < n; i++) {
// Flag to check if the current
// character is repeated
boolean repeated = false;
// Check if the current character is the same as
// the next one
while (i + 1 < n
&& s.charAt(i) == s.charAt(i + 1)) {
// Mark as repeated
repeated = true;
// 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.append(s.charAt(i));
}
// If no changes were made, return the
// result string
if (n == sb.length())
return sb.toString();
// Otherwise, recursively call the function
// to check for more duplicates
return rremove(sb.toString());
}
public static void main(String[] args){
String s = "geeksforgeek";
String result = rremove(s);
System.out.println(result);
}
}
Python
# Function to recursively remove adjacent duplicates
def rremove(s):
# Initialize result string
sb = ""
# Get the size of the input string
n = len(s)
# Iterate over the length of current string
i = 0
while i < n:
# Flag to check if the current character
# is repeated
repeated = False
# Check if the current characte
# r is the same as the next one
while i + 1 < n and s[i] == s[i + 1]:
# Mark as repeated
repeated = True
# Skip the next character since
# it's a duplicate
i += 1
# If the character was not repeated,
# add it to the result string
if not repeated:
sb += s[i]
i += 1
# If no changes were made, return the result
# string
if n == len(sb):
return sb
# Otherwise, recursively call the function \
# to check for more duplicates
return rremove(sb)
s = "geeksforgeek"
result = rremove(s)
print(result)
C#
using System;
class GfG {
// Function to recursively remove adjacent duplicates
static string rremove(string s)
{
// Initialize result string
string sb = "";
// Get the size of the input string
int n = s.Length;
// Iterate over the length of current string
for (int i = 0; i < n; i++) {
// Flag to check if the current character is
// repeated
bool repeated = false;
// Check if the current character is the same as
// the next one
while (i + 1 < n && s[i] == s[i + 1]) {
// Mark as repeated
repeated = true;
// 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 were made, return the result string
if (n == sb.Length)
return sb;
// Otherwise, recursively call the function to check
// for more duplicates
return rremove(sb);
}
static void Main(){
string s = "geeksforgeek";
string result = rremove(s);
Console.WriteLine(result);
}
}
JavaScript
// Function to recursively remove adjacent duplicates
function rremove(s)
{
// Initialize result string
let sb = "";
// Get the size of the input string
let n = s.length;
// Iterate over the length of current string
for (let i = 0; i < n; i++) {
// Flag to check if the current character is
// repeated
let repeated = false;
// Check if the current character is the same as the
// next one
while (i + 1 < n && s[i] === s[i + 1]) {
// Mark as repeated
repeated = true;
// 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 were made, return the result string
if (n === sb.length)
return sb;
// Otherwise, recursively call the function to check for
// more duplicates
return rremove(sb);
}
let s = "geeksforgeek";
let result = rremove(s);
console.log(result);
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
#include <stdio.h>
#include <string.h>
// Helper function to remove adjacent duplicates
void remove_util(char* str, int n) {
// Get the length of the string
int len = strlen(str);
// 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[k] = '\0';
// 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
void rremove(char* s) {
// Call the helper function
remove_util(s, strlen(s));
}
int main() {
char s[] = "geeksforgeek";
rremove(s);
printf("%s\n", s);
return 0;
}
Java
public class GfG {
// Helper function to remove adjacent duplicates
static void removeUtil(StringBuilder str, int n){
// 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.charAt(i) == str.charAt(i + 1)) {
// Skip all the adjacent duplicates
while (i < n - 1
&& str.charAt(i)
== str.charAt(i + 1)) {
i++;
}
}
else {
// If not a duplicate, store the character
str.setCharAt(k++, str.charAt(i));
}
}
// Remove the remaining characters from the original
// string
str.setLength(k);
// If any adjacent duplicates were removed,
// recursively check for more
if (k != n)
removeUtil(str, k);
}
// Function to initiate the removal of adjacent
// duplicates
static String rremove(String s){
StringBuilder str = new StringBuilder(s);
// Call the helper function
removeUtil(str, str.length());
// Return the modified string
return str.toString();
}
public static void main(String[] args){
String s = "geeksforgeek";
System.out.println(rremove(s));
}
}
Python
# Helper function to remove adjacent duplicates
def remove_util(s, n):
# Index to store the result string
k = 0
# Iterate over the string to remove adjacent
# duplicates
i = 0
while i < n:
# Check if the current character is the
# same as the next one
if i < n - 1 and s[i] == s[i + 1]:
# Skip all the adjacent duplicates
while i < n - 1 and s[i] == s[i + 1]:
i += 1
else:
# If not a duplicate, store the character
s[k] = s[i]
k += 1
i += 1
# Remove the remaining characters from
# the original string
s = s[:k]
# If any adjacent duplicates were removed,
# recursively check for more
if k != n:
s = remove_util(list(s), k)
return s
# Function to initiate the removal of adjacent duplicates
def rremove(s):
# Convert the string to a list to allow modification
s = list(s)
# Call the helper function
return ''.join(remove_util(s, len(s)))
# Example usage
s = "geeksforgeek"
print(rremove(s))
C#
using System;
using System.Text;
class GfG {
// Helper function to remove adjacent duplicates
static void RemoveUtil(StringBuilder str, int n)
{
// 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.Length = k;
// If any adjacent duplicates were removed,
// recursively check for more
if (k != n)
RemoveUtil(str, k);
}
// Function to initiate the removal of adjacent
// duplicates
static string RRemove(string s)
{
StringBuilder str = new StringBuilder(s);
// Call the helper function
RemoveUtil(str, str.Length);
// Return the modified string
return str.ToString();
}
static void Main()
{
string s = "geeksforgeek";
Console.WriteLine(RRemove(s));
}
}
JavaScript
// Helper function to remove adjacent duplicates
function removeUtil(str, n) {
let k = 0;
let result = [];
// Iterate over the string to remove adjacent
// duplicates
for (let 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
result[k++] = str[i];
}
}
// If any adjacent duplicates were removed,
// recursively check for more
if (k !== n) {
return removeUtil(result.join(''), k);
}
return result.join('');
}
// Function to initiate the removal of adjacent
// duplicates
function rremove(s) {
// Call the helper function
return removeUtil(s, s.length);
}
let s = "geeksforgeek";
console.log(rremove(s));
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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem