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.
- Return maximum occurring character in an input string
- Print all the duplicates in the input string
- Remove characters from the first string which are present in the second string
- Remove duplicates from a given string
- Print reverse of a string using recursion
- Write a program to print all permutations of a given string
- Divide a string in N equal parts
- Given a string, find its first non-repeating character
- Write a program to reverse an array or string
- Reverse words in a given string
- Find the smallest window in a string containing all characters of another string
- Lexicographic rank of a string
- An in-place algorithm for String Transformation
- Count words in a given string
- String matching where one string contains wildcard characters