Seg fault in this code of leetcode

string removeDuplicateLetters(string s) {

    int arr[126]={0};
    int n=s.length();
    for(int i=0;i<n;i++)
    {
        arr[s[i]]+=1;
    }
    stack<char>s1;
    int i=1;
    s1.push(s[0]);
    while(i<s.length())
    {
        char ch=s[i];
        while(s1.top()>ch and !s1.empty())
        {
            if( arr[s1.top()]>1)
            {
                s1.pop();
            }
        }
        s1.push(s[i]);
        i++;
    }
    string ans="";
    while(!s1.empty())
    {
        ans=s1.top()+ans;
        s1.pop();
    }
    return ans;
}

Hello @singhsimran567 could you please share the question link.

@singhsimran567 the problem is in this:
while(s1.top()>ch and !s1.empty())
{
if( arr[s1.top()]>1)
{
s1.pop();
}
}
when you will go inside this loop :
then there is no condition which will stop this.
That’s why you are getting this error.
like: “bcabc”
after bc when a will come that while condition will become true and you will then not be able to come out of it.
Happy Learning!!

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.