![]() |
VOOZH | about |
Given a string S which consists of only lowercase English alphabets, the task is to remove the first repeating character, reverse it, and repeat until there are no repeating characters. Return the final string.
Examples:
Input: S = "abab"
Output: ba
Explanation: In 1st operation: The first non repeating character is a. After Removing the first character, S = "bab". After Reversing the string, S = "bab".
In 2nd operation: The first non repeating character is b. After Removing the first character, S = "ab". After Reversing the string, S = "ba". Now the string S does not contain any repeating character.Input: S = "dddd"
Output: d
Approach: To solve the problem follow the below idea:
- The first repeating character must be eliminated, and then the string must be turned around. Hence, the first action is performed from the front side of the string, and the second operation is performed from the rear side of the string.
- We will use two pointer approach. Iterate the string and for each character, check if the character has not been encountered already, move the pointer forward, else reverse the pointers and repeat the process.
Follow the steps to solve the problem:
Below is the code implementation of the above approach:
ba
Time Complexity: O(N), where N is the length of the string
Auxiliary Space: O(K), K ≤ 26.