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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.