100% FASTER 99.97% SPACE EFFICIENT EXPLAINED!!!
PLS UPVOTE if you like the SOLUTION:)\n\nTHE QUESTION IS exactly same as REMOVE DUPLICATE LETTERS so you can try it also:)\n\nIDEA:-\n\n We use a STACK in the f
**PLS UPVOTE if you like the SOLUTION:)**\n\nTHE QUESTION IS exactly same as REMOVE DUPLICATE LETTERS so you can try it also:)\n\n**IDEA:-**\n\n* We use a STACK in the form of a string for this problem.\n* Also we use a vector of bool vec whose purpose is to determine which distinct elements are present in the stack currently and this vector is initialised with false.\n* WE also use another vector of int last that stores the last occurence of the corresponding characters.\n\n**DIVING INTO THE CODE.**\n\n* So, first loop is to set up our last vector.\n* Then another for loop is the main loop.\n* IF the stack is empty we simply push the element into the stack and mark it in the vec.\n* If the current element is not present in our stack then we check our top element of the stack(i.e the last element for the string that is acting as the stack) whether its greater than the current element that we are processing right now and further we need to satisfy one condition that if its greater then we need to pop but that element to be popped should appear later also and thats where our last vector comes in.\n* So, by using that if it satisfies that there is an occurence of that element later also then we pop.\n* IF the element is not greater now then we need to push the element and mark it in the vec as well.\n* NOW you can take a look at the code to understand completely:)\n\n**T.C:-** O(N)     **S.C:-** O(N)\n\n```\nclass Solution {\npublic:\n    string removeDuplicateLetters(string s) {\n        string st;\n        vector<bool>vec(26,0);\n        vector<int>last(26,0);\n        for(int i{0};i<s.length();++i){\n            last.at(s[i]-\'a\')=i;\n        }\n        for(int i{0};i<s.length();++i){\n            if(st.length()==0){\n                st.push_back(s[i]);\n                vec.at(s[i]-\'a\')=1;\n            }else if(vec.at(s[i]-\'a\')==0){\n                while(st.length() && st.back()>s[i]){\n                    if(last.at(st.back()-\'a\')>i){\n                        vec.at(st.back()-\'a\')=0;\n                        st.pop_back();\n                    }else{\n                        break;\n                    }\n                }\n                st.push_back(s[i]);\n                vec.at(s[i]-\'a\')=1;\n            }\n        }\n        return st;        \n    }\n};\n```
['String', 'Stack', 'C']