Given a string S, The task is to remove all the consecutive duplicate characters of the string and return the resultant string.
Note: that this problem is different from Recursively remove all adjacent duplicates. Here we keep one character and remove all subsequent same characters.
Examples:
Input: S= “aaaaabbbbbb”
Output: abInput: S = “neveropen”
Output: geksforgeksInput: S = “aabccba”
Output: abcba
Remove all consecutive duplicates from the string using sliding window:
Approach:
1) Input String S.
2) Initialize two pointer i, j and empty string new_elements.
3) Traverse the String Using j.
4) Compare the elements s[i] and s[j].
(i) if both elements are same skip .
(ii) if both elements are not same then append into new_elements set and slide over the window.
5) After Traversing return result.
C++14
#include <iostream> #include <string> using namespace std; string deleteConsecutiveStrings(string s) { // Initialize start and stop pointers int i = 0; int j = 0; // Initialize an empty string for new elements string newElements = "" ; // Iterate string using j pointer while (j < s.length()) { // If both elements are same then skip if (s[i] == s[j]) { j++; } // If both elements are not same then append new element else if (s[j] != s[i] || j == s.length() - 1) { newElements += s[i]; // After appending, slide over the window i = j; j++; } } // Append the last string newElements += s[j - 1]; return newElements; } int main() { // Input string s = "neveropen for neveropen is best" ; // Printing original string cout << "Input : " << s << endl; // Printing result cout << "Output : " << deleteConsecutiveStrings(s) << endl; return 0; } |
Java
// Java program to remove consecutive strings public class ConsecutiveStrings { public static String deleteConsecutiveStrings(String s) { // Initialize start and stop pointers int i = 0 ; int j = 0 ; // Initialize an empty string for new elements String newElements = "" ; // Iterate string using j pointer while (j < s.length()) { // If both elements are same then skip if (s.charAt(i) == s.charAt(j)) { j++; } // If both elements are not same then append new // element else if (s.charAt(j) != s.charAt(i) || j == s.length() - 1 ) { newElements += s.charAt(i); // After appending, slide over the window i = j; j++; } } // Append the last string newElements += s.charAt(j - 1 ); return newElements; } public static void main(String[] args) { // Input String s = "neveropen for neveropen is best" ; // Printing original string System.out.println( "Input : " + s); // Printing result System.out.println( "Output : " + deleteConsecutiveStrings(s)); } } |
Python3
#Python program to remove consecutive strings. def delete_consecutive_strings(s): #Initialize Start and Stop Pointers. i = 0 j = 0 #Initialize an empty string for new elements. new_elements = '' #Iterate String Using j pointer. while (j< len (s)): #If both elements are same then skip. if ( s[i] = = s[j] ): j + = 1 #If both elements are not same then append new element. elif ((s[j]! = s[i]) or (j = = len (s) - 1 )): new_elements + = s[i] #After appending sliding over the window. i = j j + = 1 #Append the last string. new_elements + = s[j - 1 ] return new_elements #Input. s = 'neveropen for neveropen is best' #Printing Original String print ( 'Input :' , s) #Printing Result. print ( 'Output :' ,delete_consecutive_strings(s)) #Code Contributed by SR.Dhanush. |
C#
// Javascript program to remove consecutive strings using System; public class Gfg { public static string deleteConsecutiveStrings( string s) { // Initialize start and stop pointers int i = 0; int j = 0; // Initialize an empty string for new elements string newElements = "" ; // Iterate string using j pointer while (j < s.Length) { // If both elements are same then skip if (s[i] == s[j]) { j++; } // If both elements are not same then append new element else if (s[j] != s[i] || j == s.Length - 1) { newElements += s[i]; // After appending, slide over the window i = j; j++; } } // Append the last string newElements += s[j - 1]; return newElements; } public static void Main() { // Input string s = "neveropen for neveropen is best" ; // Printing original string Console.WriteLine( "Input : " + s); // Printing result Console.WriteLine( "Output : " + deleteConsecutiveStrings(s)); } } |
Javascript
// Javascript equivalent // #Function to remove consecutive strings. function delete_consecutive_strings(s) { // Initialize Start and Stop Pointers. let i = 0; let j = 0; // Initialize an empty string for new elements. let new_elements = '' ; // Iterate String Using j pointer. while (j < s.length) { // If both elements are same then skip. if (s[i] == s[j]) { j++; // If both elements are not same then append new element. } else if ((s[j] != s[i]) || (j == s.length - 1)) { new_elements += s[i]; // After appending sliding over the window. i = j; j++; } } // Append the last string. new_elements += s[j - 1]; return new_elements; } // Input. let s = 'neveropen for neveropen is best' ; // Printing Original String console.log( 'Input :' , s); // Printing Result. console.log( 'Output :' , delete_consecutive_strings(s)); |
Input : neveropen for neveropen is best Output : geks for geks is best
Time Complexity: O(N)
Auxiliary Space: O(1)
Remove all consecutive duplicates from the string using recursion:
Approach:
If the string is not empty compare the adjacent characters of the string. If they are the same then shift the characters one by one to the left. Call recursion on string S otherwise, call recursion from S+1 string.
Follow the below steps to implement the idea:
- If the string is empty, return.
- Else compare the adjacent characters of the string. If they are the same then shift the characters one by one to the left. Call recursion on string S
- If they are not same then call recursion from S+1 string.
Illustration:
The recursion tree for the string S = aabcca is shown below.
aabcca S = aabcca
/
abcca S = abcca
/
bcca S = abcca
/
cca S = abcca
/
ca S = abca
/
a S = abca (Output String)
/
empty string
Below is the implementation of the above approach:
C++
// Recursive Program to remove consecutive // duplicates from string S. #include <bits/stdc++.h> using namespace std; // A recursive function that removes // consecutive duplicates from string S void removeDuplicates( char * S) { // When string is empty, return if (S[0] == '\0' ) return ; // if the adjacent characters are same if (S[0] == S[1]) { // Shift character by one to left int i = 0; while (S[i] != '\0' ) { S[i] = S[i + 1]; i++; } // Check on Updated String S removeDuplicates(S); } // If the adjacent characters are not same // Check from S+1 string address removeDuplicates(S + 1); } // Driver Program int main() { char S1[] = "neveropen" ; removeDuplicates(S1); cout << S1 << endl; char S2[] = "aabcca" ; removeDuplicates(S2); cout << S2 << endl; return 0; } |
Java
/*package whatever //do not write package name here */ import java.io.*; class GFG { public static String removeConsecutiveDuplicates(String input) { if (input.length() <= 1 ) return input; if (input.charAt( 0 ) == input.charAt( 1 )) return removeConsecutiveDuplicates( input.substring( 1 )); else return input.charAt( 0 ) + removeConsecutiveDuplicates( input.substring( 1 )); } public static void main(String[] args) { String S1 = "neveropen" ; System.out.println(removeConsecutiveDuplicates(S1)); String S2 = "aabcca" ; System.out.println(removeConsecutiveDuplicates(S2)); } } |
Python3
# Recursive Program to remove consecutive # duplicates from string S. def removeConsecutiveDuplicates(s): if len (s) < 2 : return s if s[ 0 ] ! = s[ 1 ]: return s[ 0 ] + removeConsecutiveDuplicates(s[ 1 :]) return removeConsecutiveDuplicates(s[ 1 :]) # This code is contributed by direwolf707 s1 = 'neveropen' print (removeConsecutiveDuplicates(s1)) # geksforgeks s2 = 'aabcca' print (removeConsecutiveDuplicates(s2)) # ab # This code is contributed by rahulsood707. |
C#
/*package whatever //do not write package name here */ using System; class GFG { public static string removeConsecutiveDuplicates( string input) { if (input.Length <= 1) return input; if (input[0] == input[1]) return removeConsecutiveDuplicates( input.Substring(1)); else return input[0] + removeConsecutiveDuplicates( input.Substring(1)); } public static void Main(String[] args) { string S1 = "neveropen" ; Console.WriteLine(removeConsecutiveDuplicates(S1)); string S2 = "aabcca" ; Console.Write(removeConsecutiveDuplicates(S2)); } } // This code is contributed by shivanisinghss2110 |
Javascript
<script> function removeConsecutiveDuplicates(input) { if (input.length<=1) return input; if (input[0]==input[1]) return removeConsecutiveDuplicates(input.substring(1)); else return input[0] + removeConsecutiveDuplicates(input.substring(1)); } let S1 = "neveropen" ; document.write(removeConsecutiveDuplicates(S1)+ "<br>" ); let S2 = "aabcca" ; document.write(removeConsecutiveDuplicates(S2)+ "<br>" ); // This code is contributed by rag2127 </script> |
geksforgeks abca
Time complexity: O(N2)
Auxiliary Space: O(N)
Remove all consecutive duplicates from the string using Iterative approach:
The idea is to check if current character is equal to the next character or not . If current character is equal to the next character we’ll ignore it and when it is not equal we will add it to our answer. At last add the last character.
Follow the below steps to implement the idea:
- Create an str string to store the result
- Iterate from 0 to string length – 2.
- If the current character is not equal to next character then add it to answer string.
- Else continue.
- return str.
Below is the implementation of above approach:
C++
// C++ program to remove consecutive // duplicates from a given string. #include <bits/stdc++.h> using namespace std; // A iterative function that removes // consecutive duplicates from string S string removeDuplicates(string s) { int n = s.length(); string str = "" ; // We don't need to do anything for // empty string. if (n == 0) return str; // Traversing string for ( int i = 0; i < n - 1; i++) { // checking if s[i] is not same as s[i+1] then add // it into str if (s[i] != s[i + 1]) { str += s[i]; } } // Since the last character will not be inserted in the // loop we add it at the end str.push_back(s[n - 1]); return str; } // Driver Program int main() { string s1 = "neveropen" ; cout << removeDuplicates(s1) << endl; string s2 = "aabcca" ; cout << removeDuplicates(s2) << endl; return 0; } |
Java
// Java program to remove consecutive // duplicates from a given string. import java.util.*; class GFG { // A iterative function that removes // consecutive duplicates from string S static void removeDuplicates( char [] S) { int n = S.length; // We don't need to do anything for // empty or single character string. if (n < 2 ) { return ; } // j is used to store index is result // string (or index of current distinct // character) int j = 0 ; // Traversing string for ( int i = 1 ; i < n; i++) { // If current character S[i] // is different from S[j] if (S[j] != S[i]) { j++; S[j] = S[i]; } } System.out.println(Arrays.copyOfRange(S, 0 , j + 1 )); } // Driver code public static void main(String[] args) { char S1[] = "neveropen" .toCharArray(); removeDuplicates(S1); char S2[] = "aabcca" .toCharArray(); removeDuplicates(S2); } } /* This code contributed by PrinciRaj1992 */ |
Python3
# Python3 program to remove consecutive # duplicates from a given string. # A iterative function that removes # consecutive duplicates from string S def removeDuplicates(S): n = len (S) # We don't need to do anything for # empty or single character string. if (n < 2 ): return # j is used to store index is result # string (or index of current distinct # character) j = 0 # Traversing string for i in range (n): # If current character S[i] # is different from S[j] if (S[j] ! = S[i]): j + = 1 S[j] = S[i] # Putting string termination # character. j + = 1 S = S[:j] return S # Driver Code if __name__ = = '__main__' : S1 = "neveropen" S1 = list (S1.rstrip()) S1 = removeDuplicates(S1) print ( * S1, sep = "") S2 = "aabcca" S2 = list (S2.rstrip()) S2 = removeDuplicates(S2) print ( * S2, sep = "") # This code is contributed by # Shubham Singh(SHUBHAMSINGH10) |
C#
// C# program to remove consecutive // duplicates from a given string. using System; class GFG { // A iterative function that removes // consecutive duplicates from string S static void removeDuplicates( char [] S) { int n = S.Length; // We don't need to do anything for // empty or single character string. if (n < 2) { return ; } // j is used to store index is result // string (or index of current distinct // character) int j = 0; // Traversing string for ( int i = 1; i < n; i++) { // If current character S[i] // is different from S[j] if (S[j] != S[i]) { j++; S[j] = S[i]; } } char [] A = new char [j + 1]; Array.Copy(S, 0, A, 0, j + 1); Console.WriteLine(A); } // Driver code public static void Main(String[] args) { char [] S1 = "neveropen" .ToCharArray(); removeDuplicates(S1); char [] S2 = "aabcca" .ToCharArray(); removeDuplicates(S2); } } // This code is contributed by 29AjayKumar |
Javascript
<script> // JavaScript program for the above approach // duplicates from a given string. // A iterative function that removes // consecutive duplicates from string S const removeDuplicates = (s) => { let n = s.length; let str = "" ; // We don't need to do anything for // empty string. if (n == 0) return str; // Traversing string for (let i = 0; i < n - 1; i++) { //checking if s[i] is not same as s[i+1] then add it into str if (s[i] != s[i + 1]) { str += s[i]; } } //Since the last character will not be inserted in the loop we add it at the end str += s[n-1]; return str; } // Driver Program let s1 = "neveropen" ; document.write(`${removeDuplicates(s1)}<br/>`) let s2 = "aabcca" ; document.write(removeDuplicates(s2)) // This code is contributed by rakeshsahni </script> |
geksforgeks abca
Time Complexity: O(N)
Auxiliary Space: O(1)
This article is contributed by Ankur Singh. If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks.
Approach#4:using regular expression
Algorithm
1.Import the re module.
2.Use the re.sub() method to replace all consecutive duplicates with a single character.
3.Return the modified string.
C++
#include <iostream> #include <regex> using namespace std; // Function to remove consecutive duplicates from a string string remove_consecutive_duplicates(string s) { // Create a regular expression pattern that matches any // character followed by one or more occurrences of the // same character regex pattern( "(.)\\1+" ); // Use the regex_replace function to replace all // occurrences of the pattern in the string with a // single occurrence of the matched character return regex_replace(s, pattern, "$1" ); } // Driver Code int main() { string s = "neveropen for neveropen is best" ; cout << remove_consecutive_duplicates(s) << endl; return 0; } // This code is Contributed by Veerendra_Singh_Rajpoot |
Java
import java.util.regex.*; class Main { // Function to remove consecutive duplicates from a // string static String removeConsecutiveDuplicates(String s) { // Create a regular expression pattern that matches // any character followed by one or more occurrences // of the same character String pattern = "(.)\\1+" ; // Use the replaceAll function to replace all // occurrences of the pattern in the string with a // single occurrence of the matched character return s.replaceAll(pattern, "$1" ); } // Driver Code public static void main(String[] args) { String s = "neveropen for neveropen is best" ; System.out.println(removeConsecutiveDuplicates(s)); } } // This code is contributed by shivamgupta0987654321 |
Python3
import re def remove_consecutive_duplicates(s): return re.sub(r '(.)\1+' , r '\1' , s) s = 'neveropen for neveropen is best' print (remove_consecutive_duplicates(s)) |
C#
using System; using System.Text.RegularExpressions; public class GFG { // Function to remove consecutive duplicates from a // string public static string RemoveConsecutiveDuplicates( string s) { // Create a regular expression pattern that matches // any character followed by one or more occurrences // of the same character Regex pattern = new Regex( "(.)\\1+" ); // Use the regex replace method to replace all // occurrences of the pattern in the string with a // single occurrence of the matched character return pattern.Replace(s, "$1" ); } // Driver Code public static void Main( string [] args) { string s = "neveropen for neveropen is best" ; Console.WriteLine(RemoveConsecutiveDuplicates(s)); } } // This code is contributed by rambabuguphka |
Javascript
// Function to remove consecutive duplicates from a string function removeConsecutiveDuplicates(s) { // Create a regular expression pattern that matches any // character followed by one or more occurrences of the // same character const pattern = /(.)\1+/g; // Use the replace method with the regex pattern to replace all // occurrences of the pattern in the string with a // single occurrence of the matched character return s.replace(pattern, "$1" ); } // Driver Code const s = "neveropen for neveropen is best" ; console.log(removeConsecutiveDuplicates(s)); // This code is contributed by shivamgupta310570 |
geks for geks is best
Time complexity: O(n)
Space complexity: O(n)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!