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++
// C++ program to remove three consecutive
// duplicates
#include <bits/stdc++.h>
using namespace std;
// function to remove three consecutive
// duplicates
void remove3ConsecutiveDuplicates(string str)
{
vector<char> v;
for (int i = 0; i < str.size(); ++i) {
v.push_back(str[i]);
if (v.size() > 2) {
int sz = v.size();
// removing three consecutive duplicates
if (v[sz - 1] == v[sz - 2] &&
v[sz - 2] == v[sz - 3]) {
v.resize(sz - 3); // Removing three characters
// from the string
}
}
}
// printing the string final string
for (int i = 0; i < v.size(); ++i)
cout << v[i];
}
// driver code
int main()
{
string str = "aabbbaccddddc";
remove3ConsecutiveDuplicates(str);
return 0;
}
Java
// Java program to remove three consecutive
// duplicates
import java.util.*;
class GFG
{
// function to remove three consecutive
// duplicates
static void remove3ConsecutiveDuplicates(String str)
{
Vector<Character> v = new Vector<>();
for (int i = 0; i < str.length(); ++i)
{
v.add(str.charAt(i));
if (v.size() > 2)
{
int sz = v.size();
// removing three consecutive duplicates
if (v.get(sz - 1) == v.get(sz - 2) &&
v.get(sz - 2) == v.get(sz - 3))
{
v.setSize(sz - 3); // Removing three characters
// from the string
}
}
}
// printing the string final string
for (int i = 0; i < v.size(); ++i)
System.out.print(v.get(i));
}
// Driver code
public static void main(String[] args)
{
String str = "aabbbaccddddc";
remove3ConsecutiveDuplicates(str);
}
}
// This code contributed by Rajput-Ji
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)
{
v.Add(str[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
<script>
// Javascript program to remove three consecutive
// duplicates
// function to remove three consecutive
// duplicates
function remove3ConsecutiveDuplicates(str)
{
let v = [];
for (let i = 0; i < str.length; ++i)
{
v.push(str[i]);
if (v.length > 2)
{
let sz = v.length;
// removing three consecutive duplicates
if (v[sz - 1] == v[sz - 2] &&
v[sz - 2] == v[sz - 3])
{
v.pop();
v.pop();
v.pop();
// Removing three characters
// from the string
}
}
}
// printing the string final string
for (let i = 0; i < v.length; ++i)
document.write(v[i]);
}
// Driver code
let str = "aabbbaccddddc";
remove3ConsecutiveDuplicates(str);
// This code is contributed by rag2127
</script>
PHP
<?php
// PHP program to remove three consecutive
// duplicates
// function to remove three consecutive
// duplicates
function remove3ConsecutiveDuplicates($str)
{
$v = array();
for ($i = 0; $i < strlen($str); ++$i)
{
array_push($v, $str[$i]);
if (count($v) > 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
?>
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++
#include <iostream>
#include <regex>
using namespace std;
// Function to remove consecutive duplicates from a string
string removeConsecutiveDuplicates(string input_str)
{
// Regular expression pattern to match consecutive
// duplicate characters
regex pattern("(\\w)\\1{2}");
// Find the first match of the pattern in the input
// string
smatch match;
bool found = regex_search(input_str, match, pattern);
// While there are consecutive duplicates found, remove
// them from the string
while (found) {
input_str = regex_replace(input_str, pattern, "");
found = regex_search(input_str, match, pattern);
}
return input_str;
}
int main()
{
string input_str = "aabbbaccddddc";
string result = removeConsecutiveDuplicates(input_str);
cout << result << endl;
return 0;
}
Java
import java.util.regex.*;
public class GFG {
// Function to remove consecutive duplicates from a
// string
static String
removeConsecutiveDuplicates(String inputStr)
{
// Regular expression pattern to match consecutive
// duplicate characters
Pattern pattern = Pattern.compile("(\\w)\\1{2}");
// Find the first match of the pattern in the input
// string
Matcher match = pattern.matcher(inputStr);
boolean found = match.find();
// While there are consecutive duplicates found,
// remove them from the string
while (found) {
inputStr = inputStr.replaceAll(
pattern.pattern(), "");
match = pattern.matcher(inputStr);
found = match.find();
}
return inputStr;
}
public static void main(String[] args)
{
String inputStr = "aabbbaccddddc";
String result
= removeConsecutiveDuplicates(inputStr);
System.out.println(result);
}
}
Python3
import re
def remove_consecutive_duplicates(input_str):
pattern = r'(\w)\1{2}'
match = re.search(pattern, input_str)
while match:
input_str = re.sub(pattern, '', input_str)
match = re.search(pattern, input_str)
return input_str
input_str = "aabbbaccddddc"
print(remove_consecutive_duplicates(input_str))
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);
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++
#include <iostream>
#include <string>
using namespace std;
string removeConsecutiveDuplicates(const string& str) {
int n = str.length();
// Create a dynamic programming table to track the counts
// of consecutive duplicates
int dp[n];
dp[0] = 1;
string result;
result.push_back(str[0]);
for (int 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.push_back(str[i]);
// If the count reaches three, remove the last three characters
if (dp[i] == 3) {
result.erase(result.length() - 3);
}
}
return result;
}
int main() {
string str1 = "aabbbaccddddc";
string result1 = removeConsecutiveDuplicates(str1);
cout << "Input: " << str1 << endl;
cout << "Output: " << result1 << endl;
string str2 = "aabbaccddc";
string result2 = removeConsecutiveDuplicates(str2);
cout << "Input: " << str2 << endl;
cout << "Output: " << result2 << endl;
return 0;
}
//This code is contributed by Sovi
Java
/*package whatever //do not write package name here */
class GFG {
public static String removeConsecutiveDuplicates(String str)
{
int n = str.length();
// Create a dynamic programming table to track the
// counts of consecutive duplicates
int[] dp = new int[n];
dp[0] = 1;
StringBuilder sb = new StringBuilder();
sb.append(str.charAt(0));
for (int 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.charAt(i) == str.charAt(i - 1)) {
dp[i] = dp[i - 1] + 1;
}
else {
dp[i] = 1;
}
// Append the current character to the result
// string
sb.append(str.charAt(i));
// If the count reaches three, remove the last
// three characters
if (dp[i] == 3) {
sb.delete(sb.length() - 3, sb.length());
}
}
return sb.toString();
}
public static void main(String[] args)
{
String str1 = "aabbbaccddddc";
String result1 = removeConsecutiveDuplicates(str1);
System.out.println("Input: " + str1);
System.out.println("Output: " + result1);
String str2 = "aabbaccddc";
String result2 = removeConsecutiveDuplicates(str2);
System.out.println("Input: " + str2);
System.out.println("Output: " + result2);
}
}
//This code is contributed by Silu
Python3
def remove_consecutive_duplicates(s):
n = len(s)
# Create a list to track the counts of consecutive duplicates
dp = [0] * n
dp[0] = 1
result = [s[0]]
for i in range(1, n):
# If the current character is the same as the previous one,
# increment the count in the dynamic programming list
if s[i] == s[i - 1]:
dp[i] = dp[i - 1] + 1
else:
dp[i] = 1
# Append the current character to the result list
result.append(s[i])
# If the count reaches three, remove the last three characters
if dp[i] == 3:
for _ in range(3):
result.pop()
return ''.join(result)
if __name__ == "__main__":
str1 = "aabbbaccddddc"
result1 = remove_consecutive_duplicates(str1)
print("Input:", str1)
print("Output:", result1)
str2 = "aabbaccddc"
result2 = remove_consecutive_duplicates(str2)
print("Input:", str2)
print("Output:", result2)
# This code is contributed by rambabuguphka
C#
using System;
class Program {
public static string
RemoveConsecutiveDuplicates(string str)
{
int n = str.Length;
// Create an array to track the counts of
// consecutive duplicates
int[] dp = new int[n];
dp[0] = 1;
string result = str[0].ToString();
for (int 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.Substring(0, result.Length
- 3);
}
}
return result;
}
static void Main()
{
string str1 = "aabbbaccddddc";
string result1 = RemoveConsecutiveDuplicates(str1);
Console.WriteLine("Input: " + str1);
Console.WriteLine("Output: " + result1);
string str2 = "aabbaccddc";
string result2 = RemoveConsecutiveDuplicates(str2);
Console.WriteLine("Input: " + str2);
Console.WriteLine("Output: " + result2);
}
}
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);
OutputInput: 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 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 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
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
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 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
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 = 2,
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 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
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