Given a string, recursively remove adjacent duplicate characters from string. The output string should not have any adjacent duplicates. See following examples.
Input: azxxzy Output: ay First "azxxzy" is reduced to "azzy". The string "azzy" contains duplicates, so it is further reduced to "ay". Input: geeksforgeeg Output: gksfor First "geeksforgeeg" is reduced to "gksforgg". The string "gksforgg" contains duplicates, so it is further reduced to "gksfor". Input: caaabbbaacdddd Output: Empty String Input: acaaabbbacdddd Output: acac
A simple approach would be to run the input string through multiple passes. In every pass remove all adjacent duplicates from left to right. Stop running passes when there are no duplicates. The worst time complexity of this method would be O(n^2).
gksforg azz c cca qpddpr acac acc
We can remove all duplicates in O(n) time.
1) Start from the leftmost character and remove duplicates at left corner if there are any.
2) The first character must be different from its adjacent now. Recur for string of length n-1 (string without first character).
3) Let the string obtained after reducing right substring of length n-1 be rem_str. There are three possible cases
……..a) If first character of rem_str matches with the first character of original string, remove the first character from rem_str.
……..b) If remaining string becomes empty and last removed character is same as first character of original string. Return empty string.
……..c) Else, append the first character of the original string at the beginning of rem_str.
4) Return rem_str.
Following are C++, Python and Java implementations of the above algorithm.
gksfor ay g a qrq acac a
Time Complexity: The time complexity of the solution can be written as T(n) = T(n-k) + O(k) where n is length of the input string and k is the number of first characters which are same. Solution of the recurrence is O(n)
Thanks to Prachi Bodke for suggesting this problem and initial solution. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Print a closest string that does not contain adjacent duplicates
- Remove duplicates from a given string
- Remove duplicates from unsorted array
- Remove duplicates from sorted array
- Remove all duplicates from a given string in Python
- Remove three consecutive duplicates from string
- Remove all consecutive duplicates from the string
- Remove duplicates from an array of small primes
- Remove duplicates from a string in O(1) extra space
- Python groupby method to remove all consecutive duplicates
- Remove duplicates from a sorted linked list using recursion
- Count occurrences of a substring recursively
- Find middle of singly linked list Recursively
- Recursively Reversing a linked list (A simple implementation)
- Decode a string recursively encoded as count followed by substring