VOOZH about

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

⇱ Remove three consecutive duplicates from string - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Remove three consecutive duplicates from string

Last Updated : 14 Jan, 2026

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 : aabbbaccddddc
Output :ccdc
Input :aabbaccddc
Output :aabbaccddc

Explanation :

We insert the characters of string one by one to vector and keep on checking the size of vector. If the size of vector is greater than 2, then we will check whether the last 3 characters of the string are same or not. If the characters are same 

Then we will move three steps backwards in array using resize() else not. 

Implementation:


Output
ccdc

Time Complexity: O(n)
Auxiliary Space: O(n)

This article is contributed by Roshni Agarwal.  

Approach#2:using re

Algorithm

1. Use the re library to search for any sequence of 3 consecutive identical characters in the input string.
2. Replace any matches with an empty string.
3. Repeat step 1 and 2 until no matches are found.


Output
ccdc

Time Complexity: O(n^2), where n is the length of the input string. This is because we could potentially iterate over the entire string multiple times (once for each match).
Space Complexity: O(n), where n is the length of the input string. This is because we need to store the input string and any intermediate regular expression matches..

Approach: Using Dynamic Programming

  • Use a DP array dp of size n, where dp[i] tracks the length of the valid string up to index i without three consecutive duplicates.
  • Traverse each character in the input:
  • Append the character to result.
  • If it’s the same as the previous character, increment dp[k]; otherwise, set dp[k] = 1.
  • If dp[k] == 3 (three consecutive duplicates), remove the last three characters from result and move k back to continue building the string. 
  • Finally, return result - the string with all triplets removed.

Output
Input: aabbbaccddddc
Output: aaaccdc
Input: aabbaccddc
Output: aabbaccddc

Time Complexity: O(n), where n is the length of the input String.

Auxiliary Space: O(n), dp table requires O(n) space to store the count of consecutive duplicates. In worst case, the space complexity will be near about O(n), where n is the length of the input String.

Comment
Article Tags:
Article Tags: