<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>

class Solution {
public:
    string removeDuplicateLetters(string s) {
        int n = s.length() ;
        vector<int> freq(26, 0) ;
        for (char ch : s) {
            freq[ch - 'a'] ++ ;
        }
        vector<char> ans ;
        vector<int> used(26, 0) ;
        for(int i = 0 ; i < n ; i ++ ) {
            if(used[s[i] - 'a']) {
                freq[s[i] - 'a'] -- ;
                continue ;
            }
            if(ans.empty()) {
            } else 
                while(!ans.empty() && ans.back() > s[i]) {
                    if (freq[ans.back() - 'a'] == 0 ) {
                        break ;
                    } else {
                        used[ans.back() - 'a'] = 0 ;
                        ans.pop_back() ;
                    }
                }
            used[s[i] - 'a'] = 1 ;
            ans.push_back(s[i]) ;
            freq[s[i] - 'a'] -- ;
        }
        string final_ans = "" ;
        for(char ch : ans) {
            final_ans += ch ;
        }
        return final_ans ;
    }
};
8500