Open In App

Remove three consecutive duplicates from string

Last Updated : 28 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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
?>

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.

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);

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.
     
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);

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.


Next Article
Article Tags :
Practice Tags :

Similar Reads