Remove three consecutive duplicates from string

Last Updated : 28 Oct, 2023

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 :aabbaccddc`
Recommended Practice

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:

Python3

 `
``# Python3 program to remove three consecutive duplicates

# function to remove three consecutive duplicates
def remove3ConsecutiveDuplicates(string):
val = ""
i = 0
while (i < len(string)):
if (i < len(string) - 2 and
string[i] * 3 == string[i:i + 3]):
i += 3
else:
val += string[i]
i += 1

if (len(val) == len(string)):
return val
else:
return remove3ConsecutiveDuplicates(val)

# Driver code
string = "aabbbaccddddc"
val = remove3ConsecutiveDuplicates(string)
print(val)

# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
`

C#

 `
``// C# program to remove three consecutive
// duplicates
using System;
using System.Collections.Generic;

class GFG
{

// function to remove three consecutive
// duplicates
static void remove3ConsecutiveDuplicates(String str)
{
List<char> v = new List<char>();
for (int i = 0; i < str.Length; ++i)
{

if (v.Count > 2)
{
int sz = v.Count;

// removing three consecutive duplicates
if (v[sz - 1] == v[sz - 2] &&
v[sz - 2] == v[sz - 3])
{
v.RemoveRange(sz-3,3); // Removing three characters
// from the string
}
}
}

// printing the string final string
for (int i = 0; i < v.Count; ++i)
Console.Write(v[i]);
}

// Driver code
public static void Main(String[] args)
{
String str = "aabbbaccddddc";
remove3ConsecutiveDuplicates(str);
}
}

// This code has been contributed by 29AjayKumar
`

Javascript

 `
`

PHP

 ` 2)` `        ``{` `            ``\$sz` `= ``count``(``\$v``);`   `            ``// removing three consecutive duplicates` `            ``if` `(``\$v``[``\$sz` `- 1] == ``\$v``[``\$sz` `- 2] && ` `                ``\$v``[``\$sz` `- 2] == ``\$v``[``\$sz` `- 3])` `            ``{` `                ``array_pop``(``\$v``);` `                ``array_pop``(``\$v``);` `                ``array_pop``(``\$v``);` `                ``// Removing three characters` `                                ``// from the string` `            ``}` `        ``}` `    ``}`   `    ``// printing the string final string` `    ``for` `(``\$i` `= 0; ``\$i` `< ``count``(``\$v``); ++``\$i``)` `        ``echo` `\$v``[``\$i``];` `}`   `    ``// Driver code` `    ``\$str` `= ``"aabbbaccddddc"``;`   `    ``remove3ConsecutiveDuplicates(``\$str``);`   `// This code is contributed by mits` `?>`

Output

```ccdc

```

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

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.

Python3

 `
``import``<``/``code> re<``/``code><``/``div>
<``/``div>
``def``<``/``code> remove_consecutive_duplicates(input_str):<``/``code><``/``div>
<``/``code>pattern <``/``code>``=``<``/``code> r<``/``code>``'(\w)\1{2}'``<``/``code><``/``div>
<``/``code>match <``/``code>``=``<``/``code> re.search(pattern, input_str)<``/``code><``/``div>
<``/``code>``while``<``/``code> match:<``/``code><``/``div>
<``/``code>input_str <``/``code>``=``<``/``code> re.sub(pattern, '', input_str)<``/``code><``/``div>
<``/``code>match <``/``code>``=``<``/``code> re.search(pattern, input_str)<``/``code><``/``div>
<``/``code>``return``<``/``code> input_str<``/``code><``/``div>
input_str <``/``code>``=``<``/``code> ``"aabbbaccddddc"``<``/``code><``/``div>
``print``<``/``code>(remove_consecutive_duplicates(input_str))<``/``code><``/``div><``/``div><``/``td><``/``tr><``/``tbody><``/``table><``/``div>`

C#

 `
``using`` System;
``using`` System.Text.RegularExpressions;

``class`` GFG {
``static`` ``string``
RemoveConsecutiveDuplicates(``string`` inputStr)
{
``string`` pattern = ``@"(\w)\1{2}"``;
Match match = Regex.Match(inputStr, pattern);
``while`` (match.Success) {
inputStr = Regex.Replace(inputStr, pattern,
``string``.Empty);
match = Regex.Match(inputStr, pattern);
}
``return`` inputStr;
}

``static`` ``void`` Main()
{
``string`` inputStr = ``"aabbbaccddddc"``;
Console.WriteLine(
RemoveConsecutiveDuplicates(inputStr));
}
}
`

Javascript

 `
``// Function to remove consecutive duplicates from a string
function removeConsecutiveDuplicates(input_str) {
// Regular expression pattern to match consecutive
// duplicate characters
const pattern = /(.)\1{2}/g;

// Find the first match of the pattern in the input
// string
let found = input_str.match(pattern);

// While there are consecutive duplicates found, remove
// them from the string
while (found) {
input_str = input_str.replace(pattern, "");
found = input_str.found(pattern);
}

return input_str;
}

const input_str = "aabbbaccddddc";
const result = removeConsecutiveDuplicates(input_str);
console.log(result);
`

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

• Define a dynamic programming desk, dp, with a size of n (the period of the enter string). Each access dp[i] will constitute the minimal variety of characters required to form the string with out 3 consecutive duplicates, considering the substring up to index i (inclusive).
• Initialize dp[0] as 1, because the minimum wide variety of characters required to form a string of length 1 is 1.
Iterate from index 1 to n-1 to fill the dynamic programming table:                                                                                      a. If the current person, str[i], isn’t like the previous person, str[i-1], then we will append str[i] to the result without introducing three consecutive duplicates. Therefore, dp[i] = dp[i-1]   1.                                                                               b. If the modern-day character, str[i], is the same as the preceding man or woman, str[i-1], we need to don’t forget  instances:
• If the previous two characters, str[i-1] and str[i-2], also are the same, we can not append str[i] to the result as it might introduce 3 consecutive duplicates. In this case, dp[i] = dp[i-1].
• If the previous two characters, str[i-1] and str[i-2], are distinct, we can append str[i] to the end result with out introducing three consecutive duplicates. In this example, dp[i] = dp[i-2]   1.
The final answer can be the string fashioned through considering the characters up to index n-1 of the enter string, aside from any characters which have a corresponding dp[i] price more than or identical to 3.

Javascript

 `function` `removeConsecutiveDuplicates(str) {` `    ``const n = str.length;` `    ``const dp = ``new` `Array(n); ``// Dynamic programming table to track consecutive duplicate counts` `    ``dp[0] = 1;`   `    ``let result = str[0];`   `    ``for` `(let i = 1; i < n; i++) {` `        ``// If the current character is the same as the previous one,` `        ``// increment the count in the dynamic programming table` `        ``if` `(str[i] === str[i - 1]) {` `            ``dp[i] = dp[i - 1] + 1;` `        ``} ``else` `{` `            ``dp[i] = 1;` `        ``}`   `        ``// Append the current character to the result string` `        ``result += str[i];`   `        ``// If the count reaches three, remove the last three characters` `        ``if` `(dp[i] === 3) {` `            ``result = result.slice(0, -3);` `        ``}` `    ``}`   `    ``return` `result;` `}`   `const str1 = ``"aabbbaccddddc"``;` `const result1 = removeConsecutiveDuplicates(str1);` `console.log(``"Input: "` `+ str1);` `console.log(``"Output: "` `+ result1);`   `const str2 = ``"aabbaccddc"``;` `const result2 = removeConsecutiveDuplicates(str2);` `console.log(``"Input: "` `+ str2);` `console.log(``"Output: "` `+ result2);`

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.

Previous
Next