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 : 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:
C++
Java
Python3
<div id = "highlighter_38248" class = "syntaxhighlighter nogutter " ><table border = "0" cellpadding = "0" cellspacing = "0" ><tbody><tr><td class = "code" ><div class = "container" ><div class = "line number1 index0 alt2" ><code class = "comments" >
|
C#
<div id= "highlighter_991065" class = "syntaxhighlighter nogutter " ><table border= "0" cellpadding= "0" cellspacing= "0" ><tbody><tr><td class = "code" ><div class = "container" ><div class = "line number1 index0 alt2" ><code class = "comments" >
|
Javascript
<div id= "highlighter_106510" class= "syntaxhighlighter nogutter " ><table border= "0" cellpadding= "0" cellspacing= "0" ><tbody><tr><td class= "code" ><div class= "container" ><div class= "line number1 index0 alt2" ><code class= "plain" ><script></code></div><div class= "line number2 index1 alt1" ><code class= "comments" >
|
PHP
<?php
function remove3ConsecutiveDuplicates( $str )
{
$v = array ();
for ( $i = 0; $i < strlen ( $str ); ++ $i )
{
array_push ( $v , $str [ $i ]);
if ( count ( $v ) > 2)
{
$sz = count ( $v );
if ( $v [ $sz - 1] == $v [ $sz - 2] &&
$v [ $sz - 2] == $v [ $sz - 3])
{
array_pop ( $v );
array_pop ( $v );
array_pop ( $v );
}
}
}
for ( $i = 0; $i < count ( $v ); ++ $i )
echo $v [ $i ];
}
$str = "aabbbaccddddc" ;
remove3ConsecutiveDuplicates( $str );
?>
|
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.
C++
Java
Python3
<div id = "highlighter_29404" class = "syntaxhighlighter nogutter " ><table border = "0" cellpadding = "0" cellspacing = "0" ><tbody><tr><td class = "code" ><div class = "container" ><div class = "line number1 index0 alt2" ><code class = "keyword" > import < / code> <code class = "plain" >re< / code>< / div><div class = "line number2 index1 alt1" > < / div><div class = "line number3 index2 alt2" ><code class = "keyword" > def < / code> <code class = "plain" >remove_consecutive_duplicates(input_str):< / code>< / div><div class = "line number4 index3 alt1" ><code class = "undefined spaces" > < / code><code class = "plain" >pattern < / code><code class = "keyword" > = < / code> <code class = "plain" >r< / code><code class = "string" > '(\w)\1{2}' < / code>< / div><div class = "line number5 index4 alt2" ><code class = "undefined spaces" > < / code><code class = "plain" >match < / code><code class = "keyword" > = < / code> <code class = "plain" >re.search(pattern, input_str)< / code>< / div><div class = "line number6 index5 alt1" ><code class = "undefined spaces" > < / code><code class = "keyword" > while < / code> <code class = "plain" >match:< / code>< / div><div class = "line number7 index6 alt2" ><code class = "undefined spaces" > < / code><code class = "plain" >input_str < / code><code class = "keyword" > = < / code> <code class = "plain" >re.sub(pattern, '', input_str)< / code>< / div><div class = "line number8 index7 alt1" ><code class = "undefined spaces" > < / code><code class = "plain" >match < / code><code class = "keyword" > = < / code> <code class = "plain" >re.search(pattern, input_str)< / code>< / div><div class = "line number9 index8 alt2" ><code class = "undefined spaces" > < / code><code class = "keyword" > return < / code> <code class = "plain" >input_str< / code>< / div><div class = "line number10 index9 alt1" ><code class = "plain" >input_str < / code><code class = "keyword" > = < / code> <code class = "string" > "aabbbaccddddc" < / code>< / div><div class = "line number11 index10 alt2" ><code class = "functions" > print < / code><code class = "plain" >(remove_consecutive_duplicates(input_str))< / code>< / div>< / div>< / td>< / tr>< / tbody>< / table>< / div>
|
C#
<div id= "highlighter_821283" class = "syntaxhighlighter nogutter " ><table border= "0" cellpadding= "0" cellspacing= "0" ><tbody><tr><td class = "code" ><div class = "container" ><div class = "line number1 index0 alt2" ><code class = "keyword" > using </code> <code class = "plain" >System;</code></div><div class = "line number2 index1 alt1" ><code class = "keyword" > using </code> <code class = "plain" >System.Text.RegularExpressions;</code></div><div class = "line number3 index2 alt2" > </div><div class = "line number4 index3 alt1" ><code class = "keyword" > class </code> <code class = "plain" >GFG {</code></div><div class = "line number5 index4 alt2" ><code class = "undefined spaces" > </code><code class = "keyword" > static </code> <code class = "keyword" > string </code></div><div class = "line number6 index5 alt1" ><code class = "undefined spaces" > </code><code class = "plain" >RemoveConsecutiveDuplicates(</code><code class = "keyword" > string </code> <code class = "plain" >inputStr)</code></div><div class = "line number7 index6 alt2" ><code class = "undefined spaces" > </code><code class = "plain" >{</code></div><div class = "line number8 index7 alt1" ><code class = "undefined spaces" > </code><code class = "keyword" > string </code> <code class = "plain" >pattern = </code><code class = "string" > @"(\w)\1{2}" </code><code class = "plain" >;</code></div><div class = "line number9 index8 alt2" ><code class = "undefined spaces" > </code><code class = "plain" >Match match = Regex.Match(inputStr, pattern);</code></div><div class = "line number10 index9 alt1" ><code class = "undefined spaces" > </code><code class = "keyword" > while </code> <code class = "plain" >(match.Success) {</code></div><div class = "line number11 index10 alt2" ><code class = "undefined spaces" > </code><code class = "plain" >inputStr = Regex.Replace(inputStr, pattern,</code></div><div class = "line number12 index11 alt1" ><code class = "undefined spaces" > </code><code class = "keyword" > string </code><code class = "plain" >.Empty);</code></div><div class = "line number13 index12 alt2" ><code class = "undefined spaces" > </code><code class = "plain" >match = Regex.Match(inputStr, pattern);</code></div><div class = "line number14 index13 alt1" ><code class = "undefined spaces" > </code><code class = "plain" >}</code></div><div class = "line number15 index14 alt2" ><code class = "undefined spaces" > </code><code class = "keyword" > return </code> <code class = "plain" >inputStr;</code></div><div class = "line number16 index15 alt1" ><code class = "undefined spaces" > </code><code class = "plain" >}</code></div><div class = "line number17 index16 alt2" > </div><div class = "line number18 index17 alt1" ><code class = "undefined spaces" > </code><code class = "keyword" > static </code> <code class = "keyword" > void </code> <code class = "plain" >Main()</code></div><div class = "line number19 index18 alt2" ><code class = "undefined spaces" > </code><code class = "plain" >{</code></div><div class = "line number20 index19 alt1" ><code class = "undefined spaces" > </code><code class = "keyword" > string </code> <code class = "plain" >inputStr = </code><code class = "string" > "aabbbaccddddc" </code><code class = "plain" >;</code></div><div class = "line number21 index20 alt2" ><code class = "undefined spaces" > </code><code class = "plain" >Console.WriteLine(</code></div><div class = "line number22 index21 alt1" ><code class = "undefined spaces" > </code><code class = "plain" >RemoveConsecutiveDuplicates(inputStr));</code></div><div class = "line number23 index22 alt2" ><code class = "undefined spaces" > </code><code class = "plain" >}</code></div><div class = "line number24 index23 alt1" ><code class = "plain" >}</code></div></div></td></tr></tbody></table></div>
|
Javascript
<div id= "highlighter_157476" class= "syntaxhighlighter nogutter " ><table border= "0" cellpadding= "0" cellspacing= "0" ><tbody><tr><td class= "code" ><div class= "container" ><div class= "line number1 index0 alt2" ><code class= "comments" >
|
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.
C++
Java
Python3
C#
Javascript
function removeConsecutiveDuplicates(str) {
const n = str.length;
const dp = new Array(n);
dp[0] = 1;
let result = str[0];
for (let i = 1; i < n; i++) {
if (str[i] === str[i - 1]) {
dp[i] = dp[i - 1] + 1;
} else {
dp[i] = 1;
}
result += str[i];
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.
Similar Reads
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 = geeksforgeeksOu
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 duplicates from Sorted Array
Given a sorted array arr[] of size n, the goal is to rearrange the array so that all distinct elements appear at the beginning in sorted order. Additionally, return the length of this distinct sorted subarray. Note: The elements after the distinct ones can be in any order and hold any value, as they
7 min read
Python groupby method to remove all consecutive duplicates
In Python, the groupby method from the itertools module provides a powerful way to group consecutive identical elements in an iterable. This functionality can be effectively utilized to remove all consecutive duplicates from a sequence. By retaining only the first occurrence of each group of identic
4 min read
Remove Duplicate/Repeated words from String
Given a string S, the task is to remove all duplicate/repeated words from the given string. Examples: Input: S = "Geeks for Geeks A Computer Science portal for Geeks" Output: Geeks for A Computer Science portal Explanation: here 'Geeks' and 'for' are duplicate so these words are removed from the str
4 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
Count distinct Strings made by removing three consecutive characters
Given a string S of length N(N > 3), the task is to count distinct strings that can be made by removing three consecutive characters from the original string. Examples: Input: S = "aaabcc"Output: 4 Explanation: "bcc", "acc", "aac", "aaa" Input: S = "aaaaa"Output: 1 Explanation: "aaa" Approach: Th
4 min read
Reduce the string by removing K consecutive identical characters
Given a string str and an integer k, the task is to reduce the string by applying the following operation any number of times until it is no longer possible: Choose a group of k consecutive identical characters and remove them from the string. Finally, print the reduced string. Examples: Input: K =
7 min read
Character replacement after removing duplicates from a string
Given a string. The task is to replace each character of the minimized string with a character present at the index 'IND' of the original string. The minimized string is the string obtained by removing all duplicates from the original string keeping the order of elements the same. IND for any index
7 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