Given a string S, remove all the consecutive duplicates. Note that this problem is different from Recursively remove all adjacent duplicates. Here we keep one character and remove all subsequent same characters.
Input : aaaaabbbbbb Output : ab Input : geeksforgeeks Output : geksforgeks Input : aabccba Output : abcba
The above problem can be solved using recursion.
- If the string is empty, return.
- Else compare the adjacent characters of the string. If they are same then shift the characters one by one to the left. Call recursion on string S
- If they not same then call recursion from S+1 string.
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:
The worst case time complexity of the above solution is O(n2). The worst case happens when all characters are same.
Iterative Solution :
The idea is to keep track of two indexes, index of current character in str and index of next distinct character in str. Whenever we see same character, we only increment current character index. We see different character, we increment index of distinct character.
Time Complexity : O(n)
Auxiliary Space : O(1)
This article is contributed by Ankur Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Remove three consecutive duplicates from string
- Python groupby method to remove all consecutive duplicates
- Remove duplicates from a given string
- Remove all duplicates from a given string in Python
- Remove duplicates from a string in O(1) extra space
- Remove duplicates from string keeping the order according to last occurrences
- Remove consecutive vowels from string
- Recursively remove all adjacent duplicates
- Remove consecutive alphabets which are in same case
- Print all the duplicates in the input string
- Character replacement after removing duplicates from a string
- Print a closest string that does not contain adjacent duplicates
- Distinct permutations of a string containing duplicates using HashSet in Java
- Remove characters from the first string which are present in the second string
- Check if a string has m consecutive 1's or 0's