VOOZH about

URL: https://www.geeksforgeeks.org/dsa/remove-consecutive-duplicates-string/

⇱ Remove all consecutive duplicates from a string - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Remove all consecutive duplicates from a string

Last Updated : 2 Feb, 2026

Given a string s , we have to remove all the consecutive duplicate characters of the string and return the resultant string. 

Examples:

Input: str = "aaaaabbbbbb"
Output: ab
Explanation: Remove consecutive duplicate characters from a string s such as 5 a's are at consecutive so only write a and same like that in b's condition.

Input: str = "geeksforgeeks"
Output: geksforgeks
Explanation: Remove consecutive duplicate characters from "geeksforgeeks", so "ee" becomes "e", resulting in "geksforgeks"

[Approach 1] Using recursion - O(n) time and O(n) space

Idea is comparing the current character with the previous character

Steps to solve the problem:

  • Compare the current character with the previous one.
  • If they are different, append the current character to the result string.
  • Move to the next index with the updated result.

Output
geksforgeks

[Expected Approach] Using Stack - 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
  • if current char is not equal to next char then add it to answer string
  • else continue
  • return string

Output
geksforgeks

[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].
  • if both element are same then skip.
  • if both element are not same then append into new string set and slide over the window
  • return the result.

Output
geksforgeks

[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

Output
geksforgeks
Comment
Article Tags:
Article Tags: