<p>Given a string <code>s</code>, remove duplicate letters so that every letter appears once and only once. You must make sure your result is <span data-keyword="lexicographically-smaller-string"><strong>the smallest in lexicographical order</strong></span> among all possible results.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;bcabc&quot;
<strong>Output:</strong> &quot;abc&quot;
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;cbacdcbc&quot;
<strong>Output:</strong> &quot;acdb&quot;
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>
	<li><code>s</code> consists of lowercase English letters.</li>
</ul>

<p>&nbsp;</p>
<p><strong>Note:</strong> This question is the same as 1081: <a href="https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/" target="_blank">https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/</a></p>

// stack + frequency + visited vector
// push the elements in inc order and if the next ele is smaller remove till the
// stack is empty or we get smaller than curr, also dont remove the element if
// the freq comes out tobe 0, dec the freq as we pushing into the stack, and
// dont push the char if it is already visited..
class Solution {
public:
    string removeDuplicateLetters(string s) {
        vector<int> f(26, 0);
        vector<int> vs(26, 0);
        stack<char> st;
        for (auto it : s)
            f[it - 'a']++;
        for (int i = 0; i < s.length(); i++) {
            char ch = s[i];
            // first dece the frq of char && mark is true and false
            f[ch - 'a']--;
            if (vs[ch - 'a'])
                continue;
            // remove the the which is not miantin curr char
            while (!st.empty() && st.top() > ch && f[st.top() - 'a'] > 0) {
                vs[st.top() - 'a']--;
                st.pop();
            }
            // Add the current char
            vs[ch - 'a']++;
            st.push(ch);
        }
        string str = "";
        while (!st.empty()) {
            str += st.top();
            st.pop();
        }
        reverse(str.begin(), str.end());
        return str;
    }
};
8900