Skip to content
Related Articles
Remove all consecutive duplicates from the string
• Difficulty Level : Easy
• Last Updated : 20 Apr, 2021

Given a string S, remove all the consecutive duplicates. Note that this problem is different from Recursively remove all adjacent duplicates. Here we keep one character and remove all subsequent same characters.
Examples:

```Input  : aaaaabbbbbb
Output : ab

Input : geeksforgeeks
Output : geksforgeks

Input : aabccba
Output : abcba```

Recursive Solution:

The above problem can be solved using recursion.

1. If the string is empty, return.
2. Else compare the adjacent characters of the string. If they are same then shift the characters one by one to the left. Call recursion on string S
3. If they not same then call recursion from S+1 string.

The recursion tree for the string S = aabcca is shown below.

```        aabcca   S = aabcca
/
abcca     S = abcca
/
bcca       S = abcca
/
cca         S = abcca
/
ca           S = abca
/
a              S = abca (Output String)
/
empty string```

Below is the implementation of the above approach:

## CPP

 `// Recursive Program to remove consecutive``// duplicates from string S.``#include ``using` `namespace` `std;` `// A recursive function that removes``// consecutive duplicates from string S``void` `removeDuplicates(``char``* S)``{``    ``// When string is empty, return``    ``if` `(S == ``'\0'``)``        ``return``;` `    ``// if the adjacent characters are same``    ``if` `(S == S) {``        ` `        ``// Shift character by one to left``        ``int` `i = 0;``        ``while` `(S[i] != ``'\0'``) {``            ``S[i] = S[i + 1];``            ``i++;``        ``}` `        ``// Check on Updated String S``        ``removeDuplicates(S);``    ``}` `    ``// If the adjacent characters are not same``    ``// Check from S+1 string address``    ``removeDuplicates(S + 1);``}` `// Driver Program``int` `main()``{``    ``char` `S1[] = ``"geeksforgeeks"``;``    ``removeDuplicates(S1);``    ``cout << S1 << endl;` `    ``char` `S2[] = ``"aabcca"``;``    ``removeDuplicates(S2);``    ``cout << S2 << endl;` `    ``return` `0;``}`

## Java

 `/*package whatever //do not write package name here */` `import` `java.io.*;` `class` `GFG {``    ``public` `static` `String removeConsecutiveDuplicates(String input) {``        ``if``(input.length()<=``1``)``            ``return` `input;``        ``if``(input.charAt(``0``)==input.charAt(``1``))``            ``return` `removeConsecutiveDuplicates(input.substring(``1``));``        ``else``            ``return` `input.charAt(``0``) + removeConsecutiveDuplicates(input.substring(``1``));``    ``}``    ``public` `static` `void` `main(String[] args)``    ``{``        ``String S1 = ``"geeksforgeeks"``;``        ``System.out.println(removeConsecutiveDuplicates(S1));``  ` `        ``String S2 = ``"aabcca"``;``        ``System.out.println(removeConsecutiveDuplicates(S2));``    ``}``}`

Output:

```geksforgeks
abca```

The worst case time complexity of the above solution is O(n2). The worst case happens when all characters are same.

Iterative Solution :

The idea is to keep track of two indexes, index of current character in str and index of next distinct character in str. Whenever we see same character, we only increment current character index. We see different character, we increment index of distinct character.

## C++

 `// C++ program to remove consecutive``// duplicates from a given string.``#include ``using` `namespace` `std;` `// A iterative function that removes ``// consecutive duplicates from string S``void` `removeDuplicates(``char` `S[]){``    ` `   ``int` `n = ``strlen``(S);` `   ``// We don't need to do anything for``   ``// empty or single character string.``   ``if` `(n < 2)``     ``return``;``   ` `   ``// j is used to store index is result``   ``// string (or index of current distinct``   ``// character) ``   ``int` `j = 0;` `   ``// Traversing string``   ``for` `(``int` `i=1; i

## Java

 `// Java program to remove consecutive``// duplicates from a given string.``import` `java.util.*;` `class` `GFG``{` `    ``// A iterative function that removes``    ``// consecutive duplicates from string S``    ``static` `void` `removeDuplicates(``char``[] S)``    ``{``        ``int` `n = S.length;` `        ``// We don't need to do anything for``        ``// empty or single character string.``        ``if` `(n < ``2``)``        ``{``            ``return``;``        ``}` `        ``// j is used to store index is result``        ``// string (or index of current distinct``        ``// character)``        ``int` `j = ``0``;` `        ``// Traversing string``        ``for` `(``int` `i = ``1``; i < n; i++)``        ``{``            ``// If current character S[i]``            ``// is different from S[j]``            ``if` `(S[j] != S[i])``            ``{``                ``j++;``                ``S[j] = S[i];``            ``}``        ``}``        ``System.out.println(Arrays.copyOfRange(S, ``0``, j + ``1``));``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``char` `S1[] = ``"geeksforgeeks"``.toCharArray();``        ``removeDuplicates(S1);` `        ``char` `S2[] = ``"aabcca"``.toCharArray();``        ``removeDuplicates(S2);``    ``}``}` `/* This code contributed by PrinciRaj1992 */`

## Python3

 `# Python3 program to remove consecutive``# duplicates from a given string.` `# A iterative function that removes``# consecutive duplicates from string S``def` `removeDuplicates(S):``        ` `    ``n ``=` `len``(S)``    ` `    ``# We don't need to do anything for``    ``# empty or single character string.``    ``if` `(n < ``2``) :``        ``return``        ` `    ``# j is used to store index is result``    ``# string (or index of current distinct``    ``# character)``    ``j ``=` `0``    ` `    ``# Traversing string``    ``for` `i ``in` `range``(n):``        ` `        ``# If current character S[i]``        ``# is different from S[j]``        ``if` `(S[j] !``=` `S[i]):``            ``j ``+``=` `1``            ``S[j] ``=` `S[i]``    ` `    ``# Putting string termination``    ``# character.``    ``j ``+``=` `1``    ``S ``=` `S[:j]``    ``return` `S``    ` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``        ` `    ``S1 ``=` `"geeksforgeeks"``    ``S1 ``=` `list``(S1.rstrip())``    ``S1 ``=` `removeDuplicates(S1)``    ``print``(``*``S1, sep ``=` `"")``        ` `    ``S2 ``=` `"aabcca"``    ``S2 ``=` `list``(S2.rstrip())``    ``S2 ``=` `removeDuplicates(S2)``    ``print``(``*``S2, sep ``=` `"")` `# This code is contributed by``# Shubham Singh(SHUBHAMSINGH10)`

## C#

 `// C# program to remove consecutive``// duplicates from a given string.``using` `System;``    ` `class` `GFG``{` `    ``// A iterative function that removes``    ``// consecutive duplicates from string S``    ``static` `void` `removeDuplicates(``char``[] S)``    ``{``        ``int` `n = S.Length;` `        ``// We don't need to do anything for``        ``// empty or single character string.``        ``if` `(n < 2)``        ``{``            ``return``;``        ``}` `        ``// j is used to store index is result``        ``// string (or index of current distinct``        ``// character)``        ``int` `j = 0;` `        ``// Traversing string``        ``for` `(``int` `i = 1; i < n; i++)``        ``{``            ``// If current character S[i]``            ``// is different from S[j]``            ``if` `(S[j] != S[i])``            ``{``                ``j++;``                ``S[j] = S[i];``            ``}``        ``}``        ``char` `[]A = ``new` `char``[j+1];``        ``Array.Copy(S,0, A, 0, j + 1);``        ``Console.WriteLine(A);``    ``}` `    ``// Driver code``    ``public` `static` `void` `Main(String[] args)``    ``{``        ``char` `[]S1 = ``"geeksforgeeks"``.ToCharArray();``        ``removeDuplicates(S1);` `        ``char` `[]S2 = ``"aabcca"``.ToCharArray();``        ``removeDuplicates(S2);``    ``}``}` `// This code is contributed by 29AjayKumar`

Output:

```geksforgeks
abca```

Time Complexity : O(n)

Auxiliary Space : O(1)

This article is contributed by Ankur Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes

My Personal Notes arrow_drop_up