Kth Character

You are given a string of lowercase alphabets. Now you need to remove all the instances of exactly one type of character such that the new string that is formed is lexicographically smallest across all the other strings that can be formed in a similar way.

For example: Let the string S be "appleap"

  • If you remove all instances of 'a' then the string formed will be : pplep
  • If you remove all instances of 'p' then the string formed will be : alea
  • If you remove all intsances of 'l' then the string formed will be : appeap
  • If you remove all instances of 'e' then the string formed will be : applap

So among all the newly formed strings , alea is lexicographically smallest string. 

Note : Lexicographically smallest means the string that would appear before all the strings if they were arranged in the order of words appearing in a dictionary.

Example:

Input: s = "appleap"
Output: alea

Approach

C++

#include <bits/stdc++.h>
using namespace std;

string kthCharacter(string s)
{

    int n = s.size();
    set<charst;
    for (int i = 0i < ni++)
        st.insert(s[i]);
    string ans = "";
    for (auto it = st.begin(); it != st.end(); it++)
    {
        string str = "";
        for (int i = 0i < ni++)
        {
            if (s[i] != *it)
                str += s[i];
        }
        if (ans == "")
            ans = str;
        else
            ans = min(ansstr);
    }
    return ans;
}
int main()
{
    string s = "appleap";

    cout << kthCharacter(s<< "\n";

    return 0;
}


No comments:

Post a Comment