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

Try It Yourself
redirect icon

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:

C++
// C++ code for the approach
#include <bits/stdc++.h>
using namespace std;

// Function to remove and reverse characters from input
// string
string removeReverse(string s)
{
    // Step 1: Convert the input string to a StringBuffer
    // and create a frequency count array Initializing
    // frequency count array
    int freq[26] = { 0 };
    // Finding frequency of each character in the input
    // string
    for (int i = 0; i < s.size(); i++) {
        char ch = s[i];
        freq[ch - 'a']++;
    }

    // Step 2: Initialize the left and right pointers, and
    // the direction counter
    int left = 0;
    int right = s.length() - 1;
    int flag = 0;

    // Step 3-6: Remove and reverse characters from input
    // string
    while (left <= right) {
        // If the counter is zero, move the left pointer,
        // otherwise, move the right pointer
        if (flag == 0) {
            // Check if the frequency count of the character
            // at the current pointer is greater than 1
            char ch = s[left];
            if (freq[ch - 'a'] == 1) {
                // If the frequency count is equal to 1,
                // move the pointer without changing
                // direction
                left++;
            }
            else {
                // Otherwise, decrement the frequency count
                // by 1 and change the direction of the
                // pointers
                freq[ch - 'a']--;
                s.replace(left, 1, "#");
                left++;
                flag ^= 1;
            }
        }
        else {
            char ch = s[right];
            if (freq[ch - 'a'] == 1) {
                right--;
            }
            else {
                freq[ch - 'a']--;
                s.replace(right, 1, "#");
                right--;
                flag ^= 1;
            }
        }
    }

    // Step 5-6: Replace non-alphabetic characters with a
    // placeholder and append alphabetic characters to a new
    // output string
    if (flag == 1)
        reverse(s.begin(), s.end());

    // Removing placeholders from the StringBuffer and
    // creating the output string
    string ans = "";
    for (int i = 0; i < s.length(); i++) {
        if (s[i] != '#')
            ans.push_back(s[i]);
    }

    // Step 7: If the counter variable is equal to 1,
    // reverse the output string before returning it
    return ans;
}

// Driver code
int main()
{
    // Taking input string from user
    string input = "abab";

    // Calling function to remove and reverse characters
    // from input string
    string output = removeReverse(input);

    // Displaying output string
    cout << output << endl;

    return 0;
}
Java
// Java code for the approach
import java.util.*;

public class Main {
    // Function to remove and reverse characters from input
    // string
    public static String removeReverse(String s) {
        // Step 1: Convert the input string to a StringBuffer
        // and create a frequency count array Initializing
        // frequency count array
        int[] freq = new int[26];
        // Finding frequency of each character in the input
        // string
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            freq[ch - 'a']++;
        }

        // Step 2: Initialize the left and right pointers, and
        // the direction counter
        int left = 0;
        int right = s.length() - 1;
        int flag = 0;

        // Step 3-6: Remove and reverse characters from input
        // string
        StringBuilder sb = new StringBuilder(s);
        while (left <= right) {
            // If the counter is zero, move the left pointer,
            // otherwise, move the right pointer
            if (flag == 0) {
                // Check if the frequency count of the character
                // at the current pointer is greater than 1
                char ch = s.charAt(left);
                if (freq[ch - 'a'] == 1) {
                    // If the frequency count is equal to 1,
                    // move the pointer without changing
                    // direction
                    left++;
                }
                else {
                    // Otherwise, decrement the frequency count
                    // by 1 and change the direction of the
                    // pointers
                    freq[ch - 'a']--;
                    sb.setCharAt(left, '#');
                    left++;
                    flag ^= 1;
                }
            }
            else {
                char ch = s.charAt(right);
                if (freq[ch - 'a'] == 1) {
                    right--;
                }
                else {
                    freq[ch - 'a']--;
                    sb.setCharAt(right, '#');
                    right--;
                    flag ^= 1;
                }
            }
        }

        // Step 5-6: Replace non-alphabetic characters with a
        // placeholder and append alphabetic characters to a new
        // output string
        s = sb.toString();
        if (flag == 1)
            reverse(sb);

        // Removing placeholders from the StringBuffer and
        // creating the output string
        String ans = "";
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i)!= '#')
                ans += s.charAt(i);
        }

        // Step 7: If the counter variable is equal to 1,
        // reverse the output string before returning it
        return ans;
    }

    // Helper function to reverse a StringBuilder
    public static void reverse(StringBuilder sb) {
        int left = 0;
        int right = sb.length() - 1;
        while (left < right) {
            char temp = sb.charAt(left);
            sb.setCharAt(left, sb.charAt(right));
            sb.setCharAt(right, temp);
            left++;
            right--;
        }
    }

    // Driver code
    public static void main(String[] args) {
        // Taking input string from user
        String input = "abab";

        // Calling function to remove and reverse characters
        // from input string
        String output = removeReverse(input);

        // Displaying output string
        System.out.println(output);
    }
}
Python
from collections import Counter


def removeReverse(s):
    # Step 1: Create a frequency count dictionary
    freq = Counter(s)

    # Step 2: Initialize the left and right pointers, and the direction counter
    left = 0
    right = len(s) - 1
    flag = 0

    # Step 3-6: Remove and reverse characters from input string
    s = list(s)
    while left <= right:
        # If the counter is zero, move the left pointer, otherwise, move the right pointer
        if flag == 0:
            ch = s[left]
            if freq[ch] == 1:
                left += 1
            else:
                freq[ch] -= 1
                s[left] = '#'
                left += 1
                flag ^= 1
        else:
            ch = s[right]
            if freq[ch] == 1:
                right -= 1
            else:
                freq[ch] -= 1
                s[right] = '#'
                right -= 1
                flag ^= 1

    s = ''.join(s)
    if flag == 1:
        s = s[::-1]

    # Removing placeholders from the string and creating the output string
    ans = ''.join([ch for ch in s if ch!= '#'])

    # Step 7: If the counter variable is equal to 1, reverse the output string before returning it
    return ans


# Driver code
input_str = "abab"
output_str = removeReverse(input_str)
print(output_str)
C#
using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static string RemoveReverse(string s)
    {
        // Step 1: Create a frequency count dictionary
        Dictionary<char, int> freq = s.GroupBy(c => c).ToDictionary(g => g.Key, g => g.Count());

        // Step 2: Initialize the left and right pointers, and the direction counter
        int left = 0;
        int right = s.Length - 1;
        int flag = 0;

        // Step 3-6: Remove and reverse characters from input string
        char[] sArray = s.ToCharArray();
        while (left <= right)
        {
            // If the counter is zero, move the left pointer, otherwise, move the right pointer
            if (flag == 0)
            {
                char ch = sArray[left];
                if (freq[ch] == 1)
                {
                    left++;
                }
                else
                {
                    freq[ch]--;
                    sArray[left] = '#';
                    left++;
                    flag ^= 1;
                }
            }
            else
            {
                char ch = sArray[right];
                if (freq[ch] == 1)
                {
                    right--;
                }
                else
                {
                    freq[ch]--;
                    sArray[right] = '#';
                    right--;
                    flag ^= 1;
                }
            }
        }

        string sModified = new string(sArray);
        if (flag == 1)
        {
            sModified = new string(sModified.Reverse().ToArray());
        }

        // Removing placeholders from the string and creating the output string
        string ans = new string(sModified.Where(ch => ch!= '#').ToArray());

        // Step 7: If the counter variable is equal to 1, reverse the output string before returning it
        return ans;
    }

    public static void Main()
    {
        string inputStr = "abab";
        string outputStr = RemoveReverse(inputStr);
        Console.WriteLine(outputStr);
    }
}
JavaScript
const removeReverse = (s) => {
    // Step 1: Create a frequency count dictionary
    let freq = {};
    for (let char of s) {
        if (freq[char]) {
            freq[char]++;
        } else {
            freq[char] = 1;
        }
    }

    // Step 2: Initialize the left and right pointers, and the direction counter
    let left = 0;
    let right = s.length - 1;
    let flag = 0;

    // Step 3-6: Remove and reverse characters from input string
    let sArray = s.split('');
    while (left <= right) {
        // If the counter is zero, move the left pointer, otherwise, move the right pointer
        if (flag === 0) {
            let ch = sArray[left];
            if (freq[ch] === 1) {
                left++;
            } else {
                freq[ch]--;
                sArray[left] = '#';
                left++;
                flag ^= 1;
            }
        } else {
            let ch = sArray[right];
            if (freq[ch] === 1) {
                right--;
            } else {
                freq[ch]--;
                sArray[right] = '#';
                right--;
                flag ^= 1;
            }
        }
    }

    let sModified = sArray.join('');
    if (flag === 1) {
        sModified = sModified.split('').reverse().join('');
    }

    // Removing placeholders from the string and creating the output string
    let ans = sModified.split('').filter(ch => ch!== '#').join('');

    // Step 7: If the counter variable is equal to 1, reverse the output string before returning it
    return ans;
};

const main = () => {
    let inputStr = 'abab';
    let outputStr = removeReverse(inputStr);
    console.log(outputStr);
};

main();

Output
ba

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

Comment