Remove all consecutive duplicates from a string
Last Updated :
11 May, 2025
Given a string s , The task is to remove all the consecutive duplicate characters of the string and return the resultant string.
Examples:
Input: s = "aaaaabbbbbb"
Output: ab
Explanation: Remove consecutive duplicate characters from a string s
such as 5 a's are at consecative so only write a and same like that in b's condition.
Input: s = "geeksforgeeks"
Output: geksforgeks
Explanation: Remove consecutive duplicate characters from a string s such as ee are their hence remove one e.
Input: s = "aabccba"
Output: abcba
Explanation: In this 2 a's are at consecutive so 1 a's remove after that 2 c's are consecutive so one c remove .
[Naive Approach] Using recursion - O(n^2) time and O(n) space
Idea is If the string is not empty compare the adjacent characters of the string. If they are the same then shift the characters one by one to the left. Call recursion on string s otherwise, 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
C++
#include <iostream>
#include <cstring>
using namespace std;
void removeDuplicates(char* s)
{
// When the string is empty or contains only one character, return
if (s[0] == '\0' || s[1] == '\0') {
return;
}
// If the adjacent characters are the same
if (s[0] == s[1]) {
// Shift characters one position to the left
int i = 0;
while (s[i] != '\0') {
s[i] = s[i + 1];
i++;
}
// Recursively check the updated string
removeDuplicates(s);
}
else {
// Otherwise, move to the next character in the string
removeDuplicates(s + 1);
}
}
int main()
{
char s1[] = "geeksforgeeks";
removeDuplicates(s1);
cout << s1 << endl;
char s2[] = "aabcca";
removeDuplicates(s2);
cout << s2 << endl;
return 0;
}
Java
import java.io.*;
class GFG {
public static String
removeDuplicates(String input)
{
if (input.length() <= 1)
return input;
if (input.charAt(0) == input.charAt(1))
return removeDuplicates(
input.substring(1));
else
return input.charAt(0)
+ removeDuplicates(
input.substring(1));
}
public static void main(String[] args)
{
String s1 = "geeksforgeeks";
System.out.println(removeDuplicates(s1));
String s2 = "aabcca";
System.out.println(removeDuplicates(s2));
}
}
Python
def removeDuplicates(s):
if len(s) < 2:
return s
if s[0] != s[1]:
return s[0]+removeDuplicates(s[1:])
return removeDuplicates(s[1:])
s1 = 'geeksforgeeks'
print(removeDuplicates(s1))
s2 = 'aabcca'
print(removeDuplicates(s2))
C#
using System;
class GFG {
public static string
removeConsecutiveDuplicates(string input)
{
if (input.Length <= 1)
return input;
if (input[0] == input[1])
return removeConsecutiveDuplicates(
input.Substring(1));
else
return input[0]
+ removeConsecutiveDuplicates(
input.Substring(1));
}
public static void Main(String[] args)
{
string s1 = "geeksforgeeks";
Console.WriteLine(removeConsecutiveDuplicates(s1));
string s2 = "aabcca";
Console.Write(removeConsecutiveDuplicates(s2));
}
}
JavaScript
function removeConsecutiveDuplicates(input)
{
if(input.length<=1)
return input;
if(input[0]==input[1])
return removeConsecutiveDuplicates(input.substring(1));
else
return input[0] +
removeConsecutiveDuplicates(input.substring(1));
}
let s1 = "geeksforgeeks";
console.log(removeConsecutiveDuplicates(s1));
let s2 = "aabcca";
console.log(removeConsecutiveDuplicates(s2));
[Expected Approach] Using Linear Traversal - O(n) time and O(n) space
Idea is Iteratively traverses the string, appending characters to a new string only if they are different from the next character, thus removing consecutive duplicates.
Step by step approach:
- Create a string to store the result
- iterate the string from 0 to length-2
1) if current char is not equal to next char then add it to answer string
2) else continue - return string
C++
#include <bits/stdc++.h>
using namespace std;
string removeDuplicates(string s)
{
int n = s.length();
string str = "";
if (n == 0)
return str;
// Traversing string
for (int i = 0; i < n - 1; i++) {
// checking if s[i] is not same as s[i+1]
// then add it into str
if (s[i] != s[i + 1]) {
str += s[i];
}
}
// Since the last character will not be inserted in the
// loop we add it at the end
str.push_back(s[n - 1]);
return str;
}
int main()
{
string s1 = "geeksforgeeks";
cout << removeDuplicates(s1) << endl;
string s2 = "aabcca";
cout << removeDuplicates(s2) << endl;
return 0;
}
Java
public class GfG {
public static String removeDuplicates(String s) {
int n = s.length();
StringBuilder str = new StringBuilder();
if (n == 0)
return str.toString();
// Traversing string
for (int i = 0; i < n - 1; i++) {
// checking if s.charAt(i) is not same
// as s.charAt(i+1) then add it into str
if (s.charAt(i) != s.charAt(i + 1)) {
str.append(s.charAt(i));
}
}
// Since the last character will not be inserted in the
// loop we add it at the end
str.append(s.charAt(n - 1));
return str.toString();
}
public static void main(String[] args) {
String s1 = "geeksforgeeks";
System.out.println(removeDuplicates(s1));
String s2 = "aabcca";
System.out.println(removeDuplicates(s2));
}
}
Python
def removeDuplicates(s):
n = len(s)
str_ = ""
if n == 0:
return str_
# Traversing string
for i in range(n - 1):
# checking if s[i] is not same as s[i+1] then add
# it into str
if s[i] != s[i + 1]:
str_ += s[i]
# Since the last character will not be inserted in the
# loop we add it at the end
str_ += s[n - 1]
return str_
if __name__ == '__main__':
s1 = "geeksforgeeks"
print(removeDuplicates(s1))
s2 = "aabcca"
print(removeDuplicates(s2))
C#
using System;
class GfG {
public static string RemoveDuplicates(string s) {
int n = s.Length;
string str = "";
if (n == 0)
return str;
// Traversing string
for (int i = 0; i < n - 1; i++) {
// checking if s[i] is not same as s[i+1] then add
// it into str
if (s[i] != s[i + 1]) {
str += s[i];
}
}
// Since the last character will not be inserted in the
// loop we add it at the end
str += s[n - 1];
return str;
}
static void Main() {
string s1 = "geeksforgeeks";
Console.WriteLine(RemoveDuplicates(s1));
string s2 = "aabcca";
Console.WriteLine(RemoveDuplicates(s2));
}
}
JavaScript
function removeDuplicates(s) {
let n = s.length;
let str = '';
if (n === 0)
return str;
// Traversing string
for (let i = 0; i < n - 1; i++) {
// checking if s[i] is not same as s[i+1] then add
// it into str
if (s[i] !== s[i + 1]) {
str += s[i];
}
}
// Since the last character will not be inserted in the
// loop we add it at the end
str += s[n - 1];
return str;
}
let s1 = 'geeksforgeeks';
console.log(removeDuplicates(s1));
let s2 = 'aabcca';
console.log(removeDuplicates(s2));
[Expected Approach] Using Sliding window - O(n) time and O(n) space
Idea is Initialize pointers i
, j
and now
traverse with j
, skip if s[i] == s[j]
, else append to new
, then return the result
Step by step approach:
- Initialize two pointer i, j and new string .
- Traverse the string using j pointer .
- Compare S[i] and S[j]
1) if both element are same then skip.
2) if both element are not same then append into new string set and slide over the window - After Traversing return result
C++
#include <iostream>
#include <string>
using namespace std;
string removeDuplicates(string s) {
// If the string is empty, return it
if (s.empty()) {
return s;
}
// Initialize the result string
string result = "";
// Iterate through the string with the sliding window
for (int i = 0; i < s.length(); i++) {
// If the result is empty or the last character
// in result is not the same as current character
if (result.empty() || result.back() != s[i]) {
result += s[i];
}
}
return result;
}
int main() {
string s1 = "geeksforgeeks";
cout << removeDuplicates(s1) << endl;
string s2 = "aabcca";
cout << removeDuplicates(s2) << endl;
return 0;
}
Java
import java.util.*;
public class GfG {
public static String removeDuplicates(String s) {
// If the string is empty, return it
if (s.isEmpty()) {
return s;
}
// Initialize the result string
StringBuilder result = new StringBuilder();
// Iterate through the string with the sliding window
for (int i = 0; i < s.length(); i++) {
// If the result is empty or the last character in result is not the same as current character
if (result.length() == 0 || result.charAt(result.length() - 1) != s.charAt(i)) {
result.append(s.charAt(i));
}
}
return result.toString();
}
public static void main(String[] args) {
String s1 = "geeksforgeeks";
System.out.println(removeDuplicates(s1));
String s2 = "aabcca";
System.out.println(removeDuplicates(s2));
}
}
Python
def removeDuplicates(s):
# If the string is empty, return it
if not s:
return s
# Initialize the result string
result = ""
# Iterate through the string with the sliding window
for i in range(len(s)):
# If the result is empty or the last character in result is not the same as current character
if not result or result[-1] != s[i]:
result += s[i]
return result
if __name__ == '__main__':
s1 = "geeksforgeeks"
print(removeDuplicates(s1))
s2 = "aabcca"
print(removeDuplicates(s2))
C#
using System;
class GfG {
static string RemoveDuplicates(string s) {
// If the string is empty, return it
if (string.IsNullOrEmpty(s)) {
return s;
}
// Initialize the result string
string result = "";
// Iterate through the string with the sliding window
for (int i = 0; i < s.Length; i++) {
// If the result is empty or the last character in result is not the same as current character
if (result.Length == 0 || result[result.Length - 1] != s[i]) {
result += s[i];
}
}
return result;
}
static void Main() {
string s1 = "geeksforgeeks";
Console.WriteLine(RemoveDuplicates(s1));
string s2 = "aabcca";
Console.WriteLine(RemoveDuplicates(s2));
}
}
JavaScript
function removeDuplicates(s) {
// If the string is empty, return it
if (s.length === 0) {
return s;
}
// Initialize the result string
let result = '';
// Iterate through the string with the sliding window
for (let i = 0; i < s.length; i++) {
// If the result is empty or the last character in result is not the same as current character
if (result.length === 0 || result[result.length - 1] !== s[i]) {
result += s[i];
}
}
return result;
}
const s1 = 'geeksforgeeks';
console.log(removeDuplicates(s1));
const s2 = 'aabcca';
console.log(removeDuplicates(s2));
[Alternate Approach] Using Regex Approach - O(n) time and O(1) space
This idea is that regular expression to match any character followed by one or more of the same character in a string. It then replaces these sequences of consecutive duplicates with just a single occurrence of that character.
Step by step approach:
- It uses a regular expression
"(.)\\1+"
to match any character followed by one or more of the same character. - The
regex_replace
function then replaces these matches with a single occurrence of that character, resulting in a string without consecutive duplicates
C++
#include <iostream>
#include <regex>
using namespace std;
string removeDuplicates(string s) {
// Create a regex pattern to match consecutive duplicate characters
regex r("(.)\\1+");
// Use regex_replace to replace consecutive duplicates with a single character
s = regex_replace(s, r, "$1");
return s;
}
int main() {
string s1 = "geeksforgeeks";
cout << removeDuplicates(s1) << endl;
string s2 = "aabcca";
cout << removeDuplicates(s2) << endl;
return 0;
}
Java
import java.util.regex.*;
public class Main {
public static String removeDuplicates(String s) {
// Create a regex pattern to match consecutive duplicate characters
Pattern p = Pattern.compile("(.)\1+");
// Use matcher to replace consecutive duplicates with a single character
Matcher m = p.matcher(s);
s = m.replaceAll("$1");
return s;
}
public static void main(String[] args) {
String s1 = "geeksforgeeks";
System.out.println(removeDuplicates(s1));
String s2 = "aabcca";
System.out.println(removeDuplicates(s2));
}
}
Python
import re
def remove_duplicates(s):
# Create a regex pattern to match consecutive duplicate characters
return re.sub(r'(.)\1+', r'\1', s)
s1 = "geeksforgeeks"
print(remove_duplicates(s1))
s2 = "aabcca"
print(remove_duplicates(s2))
C#
using System;
using System.Text.RegularExpressions;
class GfG {
// Method to remove consecutive duplicates using regex
static string RemoveDuplicates(string s) {
// Create a regex pattern to match consecutive duplicate characters
return Regex.Replace(s, "(.)\\1+", "$1");
}
// Main method to test the solution
static void Main() {
string s1 = "geeksforgeeks";
Console.WriteLine(RemoveDuplicates(s1));
string s2 = "aabcca";
Console.WriteLine(RemoveDuplicates(s2));
}
}
JavaScript
function removeDuplicates(s) {
// Create a regex pattern to match consecutive duplicate characters
return s.replace(/(.)\1+/g, '$1');
}
let s1 = "geeksforgeeks";
console.log(removeDuplicates(s1));
let s2 = "aabcca";
console.log(removeDuplicates(s2));
Similar Reads
Remove all consecutive duplicates from the string Given a string s , The task is to remove all the consecutive duplicate characters of the string and return the resultant string. Examples: Input: s = "aaaaabbbbbb"Output: abExplanation: Remove consecutive duplicate characters from a string s such as 5 a's are at consecative so only write a and same
10 min read
Remove three consecutive duplicates from string Given a string, you have to remove the three consecutive duplicates from the string. If no three are consecutive then output the string as it is. Examples: Input : aabbbaccddddcOutput :ccdcInput :aabbaccddcOutput :aabbaccddcRecommended PracticeThree consecutive duplicatesTry It!Explanation : We inse
12 min read
Remove duplicates from a string Given a string s which may contain lowercase and uppercase characters. The task is to remove all duplicate characters from the string and find the resultant string. Note: The order of remaining characters in the output should be the same as in the original string.Example:Input: s = geeksforgeeksOutp
10 min read
Check if string is palindrome after removing all consecutive duplicates Given a string str, the task is to remove all the consecutive duplicates from the string str and check if the final string is palindrome or not. Print "Yes" if it is a palindromic else print "No". Examples: Input: str = "abbcbbbaaa" Output: Yes Explanation: On removing all consecutive duplicates cha
7 min read
Remove All Duplicates from a Given String in Python The task of removing all duplicates from a given string in Python involves retaining only the first occurrence of each character while preserving the original order. Given an input string, the goal is to eliminate repeated characters and return a new string with unique characters. For example, with
2 min read
Remove consecutive vowels from string Given a string s of lowercase letters, we need to remove consecutive vowels from the string Note : Sentence should not contain two consecutive vowels ( a, e, i, o, u). Examples : Input: geeks for geeksOutput: geks for geksInput : your article is in queue Output : yor article is in quApproach: Iterat
15+ min read
Remove All Adjacent Duplicates in String II Given a string s and an integer k, the task is to repeatedly delete k adjacent duplicates till no deletions are possible and then return the final string. On deletion of k adjacent duplicates, the left and right sides of the deleted substring is concatenated together. Examples: Input: s = "abcd", k
3 min read
Remove all duplicate adjacent characters from a string using Stack Given a string, str, the task is to remove all the duplicate adjacent characters from the given string. Examples: Input: str= âazxxzyâOutput: ay Removal of "xx" modifies the string to âazzyâ. Now, the removal of "zz" modifies the string to âayâ. Since the string âayâ doesn't contain duplicates, the
6 min read
Remove duplicates from a string in O(1) extra space Given a string str of lowercase characters, the task is to remove duplicates and return a resultant string without modifying the order of characters in the original string. Examples: Input: str = "geeksforgeeks" Output: geksfor Input: str = "characters" Output: chartes Approach: The idea is to use b
13 min read
Print all the duplicate characters in a string Given a string s, the task is to identify all characters that appear more than once and print each as a list containing the character and its count. Examples:Input: s = "geeksforgeeks"Output: ['e', 4], ['g', 2], ['k', 2], ['s', 2]Explanation: Characters e, g, k, and s appear more than once. Their co
8 min read