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++ program to remove three consecutive
// duplicates
#include <bits/stdc++.h>
using namespace std;
// function to remove three consecutive
// duplicates
void removeTriplets(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";
removeTriplets(str);
return 0;
}
// Java program to remove three consecutive
// duplicates
import java.util.*;
class GFG
{
// function to remove three consecutive
// duplicates
static void removeTriplets(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";
removeTriplets(str);
}
}
// This code contributed by Rajput-Ji
# Python3 program to remove three consecutive duplicates
# function to remove three consecutive duplicates
def removeTriplets(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 removeTriplets(val)
# Driver code
string = "aabbbaccddddc"
val = removeTriplets(string)
print(val)
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
// C# program to remove three consecutive
// duplicates
using System;
using System.Collections.Generic;
class GFG
{
// function to remove three consecutive
// duplicates
static void removeTriplets(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";
removeTriplets(str);
}
}
// This code has been contributed by 29AjayKumar
<script>
// Javascript program to remove three consecutive
// duplicates
function removeTriplets(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";
removeTriplets(str);
// This code is contributed by rag2127
</script>
<?php
// PHP program to remove three consecutive
// duplicates
// function to remove three consecutive
// duplicates
function removeTriplets($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";
removeTriplets($str);
// This code is contributed by mits
?>
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.
#include <iostream>
#include <regex>
using namespace std;
// Function to remove consecutive duplicates from a string
string removeTriplets(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 = removeTriplets(input_str);
cout << result << endl;
return 0;
}
import java.util.regex.*;
public class GFG {
// Function to remove consecutive duplicates from a
// string
static String
removeTriplets(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
= removeTriplets(inputStr);
System.out.println(result);
}
}
import re
def removeTriplets(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(removeTriplets(input_str))
using System;
using System.Text.RegularExpressions;
class GFG {
static string
removeTriplets(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(
removeTriplets(inputStr));
}
}
// Function to remove consecutive duplicates from a string
function removeTriplets(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 = removeTriplets(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
- 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 fromresultand movekback to continue building the string. - Finally, return result - the string with all triplets removed.
#include <iostream>
#include <string>
using namespace std;
string removeTriplets(const string& str) {
int n = str.length();
string result = "";
vector<int> dp(n, 0);
// index for result
int k = 0;
for (int i = 0; i < n; i++) {
result.push_back(str[i]);
if (k == 0 || result[k] != result[k - 1])
dp[k] = 1;
else
dp[k] = dp[k - 1] + 1;
// If three consecutive duplicates found
if (dp[k] == 3) {
// Remove last 3 characters
result.erase(result.end() - 3, result.end());
// Move pointer back accordingly
k -= 2;
}
else {
k++;
}
}
return result;
}
int main() {
string str1 = "aabbbaccddddc";
string result1 = removeTriplets(str1);
cout << "Input: " << str1 << endl;
cout << "Output: " << result1 << endl;
string str2 = "aabbaccddc";
string result2 = removeTriplets(str2);
cout << "Input: " << str2 << endl;
cout << "Output: " << result2 << endl;
return 0;
}
//This code is contributed by Sovi
class GFG {
public static String removeTriplets(String str)
{
int n = str.length();
StringBuilder result = new StringBuilder();
int[] dp = new int[n];
int k = 0; // index for result
for (int i = 0; i < n; i++) {
result.append(str.charAt(i));
if (k == 0 || result.charAt(k) != result.charAt(k - 1))
dp[k] = 1;
else
dp[k] = dp[k - 1] + 1;
// If three consecutive duplicates found
if (dp[k] == 3) {
// Remove last 3 characters
result.delete(result.length() - 3, result.length());
// Adjust index after deletion
k -= 2;
}
else {
k++;
}
}
return result.toString();
}
public static void main(String[] args)
{
String str1 = "aabbbaccddddc";
String result1 = removeTriplets(str1);
System.out.println("Input: " + str1);
System.out.println("Output: " + result1);
String str2 = "aabbaccddc";
String result2 = removeTriplets(str2);
System.out.println("Input: " + str2);
System.out.println("Output: " + result2);
}
}
//This code is contributed by Silu
def removeTriplets(s):
n = len(s)
result = []
dp = []
for i, c in enumerate(s):
result.append(c)
# Determine consecutive count
if len(result) == 1 or result[-1] != result[-2]:
dp.append(1)
else:
dp.append(dp[-1] + 1)
# If three consecutive duplicates found
if dp[-1] == 3:
# Remove last 3 characters
result = result[:-3]
# keep dp in sync
dp = dp[:-3]
return ''.join(result)
if __name__ == "__main__":
str1 = "aabbbaccddddc"
result1 = removeTriplets(str1)
print("Input:", str1)
print("Output:", result1)
str2 = "aabbaccddc"
result2 = removeTriplets(str2)
print("Input:", str2)
print("Output:", result2)
# This code is contributed by rambabuguphka
using System;
using System.Text;
using System.Collections.Generic;
class Program {
public static string removeTriplets(string str)
{
int n = str.Length;
var result = new StringBuilder();
var dp = new List<int>();
for (int i = 0; i < n; i++)
{
result.Append(str[i]);
// Determine consecutive count
if (result.Length == 1 || result[result.Length - 1] != result[result.Length - 2])
{
dp.Add(1);
}
else
{
dp.Add(dp[dp.Count - 1] + 1);
}
// If three consecutive duplicates found
if (dp[dp.Count - 1] == 3)
{
// Remove last 3 characters
result.Length -= 3;
// keep dp in sync
dp.RemoveRange(dp.Count - 3, 3);
}
}
return result.ToString();
}
static void Main()
{
string str1 = "aabbbaccddddc";
string result1 = removeTriplets(str1);
Console.WriteLine("Input: " + str1);
Console.WriteLine("Output: " + result1);
string str2 = "aabbaccddc";
string result2 = removeTriplets(str2);
Console.WriteLine("Input: " + str2);
Console.WriteLine("Output: " + result2);
}
}
function removeTriplets(str) {
const n = str.length;
let result = "";
let dp = [];
for (let i = 0; i < n; i++) {
result += str[i];
// Determine consecutive count
if (result.length === 1 || result[result.length - 1] !== result[result.length - 2]) {
dp.push(1);
} else {
dp.push(dp[dp.length - 1] + 1);
}
// If three consecutive duplicates found
if (dp[dp.length - 1] === 3) {
// Remove last 3 characters
result = result.slice(0, -3);
// keep dp in sync
dp.splice(-3, 3);
}
}
return result;
}
const str1 = "aabbbaccddddc";
const result1 = removeTriplets(str1);
console.log("Input: " + str1);
console.log("Output: " + result1);
const str2 = "aabbaccddc";
const result2 = removeTriplets(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.