VOOZH about

URL: https://www.geeksforgeeks.org/dsa/remove-repeating-chars-and-reverse-string-until-no-repetitions/

⇱ Remove Repeating chars and Reverse String until no Repetitions - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Remove Repeating chars and Reverse String until no Repetitions

Last Updated : 7 Feb, 2026

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:

  • Initialize a frequency array freq to keep track of the frequency of each character in the input string.
  • Initialize the left and right pointers to the start and end indices of the input string, respectively.
    • l = 0, r = s.length() - 1
  • Initialize a flag f to 0.
  • Iterate over the string while l ≤ r,
    • If f = 0, check if the frequency count of the character at the current pointer is equal to 1, move the left pointer, else decrement the frequency count by 1, and replace the character at position l with a '#', increment l and change the value of flag f by using the XOR operator.
    • If the frequency count is equal to 1, move the pointer without changing direction.
    • If f = 1, check if the frequency count of the character at the current pointer is equal to 1, move the right pointer, else decrement r by 1, and replace the character at position r with a '#' and change the value of the flag.
  • Check if f = 0. reverse the string.
  • Iterate over the input string and append all alphabetic characters to a new output string ans.
  • Return string ans.

Below is the code implementation of the above approach:


Output
ba

Time Complexity: O(N), where N is the length of the string
Auxiliary Space: O(K), K ≤ 26.

Comment
Article Tags: