Given a string, recursively remove adjacent duplicate characters from the string. The output string should not have any adjacent duplicates. See following examples.
First “azxxzy” is reduced to “azzy”.
The string “azzy” contains duplicates,
so it is further reduced to “ay”.
First “geeksforgeeg” is reduced to
“gksforgg”. The string “gksforgg”
contains duplicates, so it is further
reduced to “gksfor”.
Output: Empty String
The following approach can be followed to remove duplicates in O(N) time:
- Start from the leftmost character and remove duplicates at left corner if there are any.
- The first character must be different from its adjacent now. Recur for string of length n-1 (string without first character).
- Let the string obtained after reducing right substring of length n-1 be rem_str. There are three possible cases
- If first character of rem_str matches with the first character of original string, remove the first character from rem_str.
- If remaining string becomes empty and last removed character is same as first character of original string. Return empty string.
- Else, append the first character of the original string at the beginning of rem_str.
- Return rem_str.
Below image is a dry run of the above approach:
Below is the implementation of the above approach:
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 sorted array
- Remove all consecutive duplicates from the string
- Remove three consecutive duplicates from string
- Remove all duplicates from a given string in Python
- Remove duplicates from unsorted array
- Remove duplicates from an array of small primes
- Remove duplicates from a string in O(1) extra space
- Remove duplicates from a sorted linked list using recursion
- Python groupby method to remove all consecutive duplicates
- Remove first adjacent pairs of similar characters until possible
- Insertion in a Trie recursively
- Count occurrences of a substring recursively
- Recursively Reversing a linked list (A simple implementation)