Find the character which remains in the end

Last Updated : 23 Jul, 2025

Given a string S containing only characters 'A' and 'B'. In one operation, one character can able to eliminate the other character which is at any position. This procedure circularly starts from index 0 to the last index until only A's or B's are left. Find out the character which remains without doing any operations on the string.

Examples:

Input: S = "ABB"
Output: "B"
Explanation: At Index 0, The 'A' will delete the 'B' at index 1 then the string becomes "AB". Index 1, The 'B' will delete the 'A' at index 0 then the string becomes "B". The character that remains is 'B'.

Input: S = "AABBB"
Output: "A"
Explanation: At Index 0, The 'A' will delete the 'B' at index 2 then the string becomes "AABB". Index 1, The 'A' will delete the 'B' at index 2 then the string becomes "AAB". Index 2, The 'B' will delete the 'A' at index 0 then the string becomes "AB". As we reached the end, again it will start from index 0. Index 0, The 'A' will delete the 'B' at index 1 then the string becomes "A". The character that remains is 'A'.

Approach: To solve the problem follow the below idea:

The idea is to maintain a queue to find the character which remains at last without deleting any character from the string.

The following are the steps to achieve the problem.

  • We will maintain two queues q1 and q2. One queue(q1) to store indexes of 'A' and the other (q2) to store indexes of 'B'.
  • Traverse the string, and push the index to q1 whenever 'A' encounters otherwise make the index to q2.
  • We will iterate the two queues until one of the queues is empty.
  • We will compare both the front values of the queue, the index with the lesser value will remain because the lesser index will delete the other index value.
  • So we will push the lesser index value again in the respective queue by adding that value with the length of the string as we have to move in a circular manner.

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;
 
// Function to obtain the character
// which remains in the end.
string FindCharacter(string S)
{
 
    // Finding the length of the string
    int n = S.size();
 
    // Initialized two queues to store
    // the indexes for 'A' and 'B'
    queue<int> q1;
    queue<int> q2;
 
    // Traverse the string to push the index
    // values with in their respective queues
    for (int i = 0; i < n; i++) {
        if (S[i] == 'A')
            q1.push(i);
        else
            q2.push(i);
    }
 
    // Traversing the queues
    while (!q1.empty() && !q2.empty()) {
        int a_index = q1.front();
        int b_index = q2.front();
 
        q1.pop();
        q2.pop();
 
        // Comparing the index values
        if (a_index < b_index)
            q1.push(a_index + n);
        else
            q2.push(b_index + n);
    }
 
    // Returning the character that
    // remains at the end
    return (q1.size() > q2.size()) ? "A" : "B";
}
 
// Driver code
int main()
{
    string S = "AABBB";
 
    // Function call
    cout << FindCharacter(S) << endl;
 
    return 0;
}
Java
import java.util.LinkedList;
import java.util.Queue;

public class Main {

    // Function to obtain the character
    // which remains in the end.
    static String findCharacter(String S) {

        // Finding the length of the string
        int n = S.length();

        // Initialized two queues to store
        // the indexes for 'A' and 'B'
        Queue<Integer> q1 = new LinkedList<>();
        Queue<Integer> q2 = new LinkedList<>();

        // Traverse the string to push the index
        // values within their respective queues
        for (int i = 0; i < n; i++) {
            if (S.charAt(i) == 'A')
                q1.add(i);
            else
                q2.add(i);
        }

        // Traversing the queues
        while (!q1.isEmpty() && !q2.isEmpty()) {
            int a_index = q1.peek();
            int b_index = q2.peek();

            q1.remove();
            q2.remove();

            // Comparing the index values
            if (a_index < b_index)
                q1.add(a_index + n);
            else
                q2.add(b_index + n);
        }

        // Returning the character that
        // remains at the end
        return (q1.size() > q2.size()) ? "A" : "B";
    }

    // Driver code
    public static void main(String[] args) {
        String S = "AABBB";

        // Function call
        System.out.println(findCharacter(S));
    }
}
Python3
# Python code addition

# Function to obtain the character
# which remains in the end.
def FindCharacter(S):
    # Finding the length of the string
    n = len(S)

    # Initialized two queues to store
    # the indexes for 'A' and 'B'
    q1 = []
    q2 = []

    # Traverse the string to push the index
    # values with in their respective queues
    for i in range(n):
        if S[i] == 'A':
            q1.append(i)
        else:
            q2.append(i)

    # Traversing the queues
    while q1 and q2:
        a_index = q1[0]
        b_index = q2[0]

        q1.pop(0)
        q2.pop(0)

        # Comparing the index values
        if a_index < b_index:
            q1.append(a_index + n)
        else:
            q2.append(b_index + n)

    # Returning the character that
    # remains at the end
    return "A" if len(q1) > len(q2) else "B"

# Driver code
S = "AABBB"

# Function call
print(FindCharacter(S))

# This code is contributed by Tapesh(tapeshdua420)
C#
using System;
using System.Collections.Generic;

namespace CodeTranslation
{
    class Program
    {
        // Function to obtain the character
        // which remains in the end.
        static string FindCharacter(string S)
        {
          
            // Finding the length of the string
            int n = S.Length;
          
            // Initialized two queues to store
            // the indexes for 'A' and 'B'
            Queue<int> q1 = new Queue<int>();
            Queue<int> q2 = new Queue<int>();

          
            // Traverse the string to push the index
            // values with in their respective queues
            for (int i = 0; i < n; i++)
            {
                if (S[i] == 'A')
                    q1.Enqueue(i);
                else
                    q2.Enqueue(i);
            }

            // Traversing the queues
            while (q1.Count > 0 && q2.Count > 0)
            {
                int a_index = q1.Peek();
                int b_index = q2.Peek();
                q1.Dequeue();
                q2.Dequeue();

              
                // Comparing the index values
                if (a_index < b_index)
                    q1.Enqueue(a_index + n);
                else
                    q2.Enqueue(b_index + n);
            }

            // Returning the character that
            // remains at the end
            return (q1.Count > q2.Count) ? "A" : "B";
        }

        // Driver code
        static void Main(string[] args)
        {
            string S = "AABBB";
            Console.WriteLine(FindCharacter(S));
        }
    }
}
JavaScript
function findCharacter(S) {

    // Finding the length of the string
    let n = S.length;

    // Initialized two queues to store
    // the indexes for 'A' and 'B'
    let q1 = [];
    let q2 = [];

    // Traverse the string to push the index
    // values within their respective queues
    for (let i = 0; i < n; i++) {
        if (S.charAt(i) === 'A')
            q1.push(i);
        else
            q2.push(i);
    }

    // Traversing the queues
    while (q1.length > 0 && q2.length > 0) {
        let aIndex = q1.shift();
        let bIndex = q2.shift();

        // Comparing the index values
        if (aIndex < bIndex)
            q1.push(aIndex + n);
        else
            q2.push(bIndex + n);
    }

    // Returning the character that
    // remains at the end
    return (q1.length > q2.length) ? "A" : "B";
}

// Driver code
let S = "AABBB";

// Function call
console.log(findCharacter(S));

Output
A

Time Complexity: O(n)
Auxiliary Space: O(n) (Both queues can take space of length n)

Comment