<p>Given a string <code>s</code>, return <em>the </em><span data-keyword="lexicographically-smaller-string"><em>lexicographically smallest</em></span> <span data-keyword="subsequence-string"><em>subsequence</em></span><em> of</em> <code>s</code> <em>that contains all the distinct characters of</em> <code>s</code> <em>exactly once</em>.</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;= 1000</code></li>
	<li><code>s</code> consists of lowercase English letters.</li>
</ul>

<p>&nbsp;</p>
<strong>Note:</strong> This question is the same as 316: <a href="https://leetcode.com/problems/remove-duplicate-letters/" target="_blank">https://leetcode.com/problems/remove-duplicate-letters/</a>
class Solution {
public:
    string smallestSubsequence(string s) {
        int n = s.size();
        unordered_map<char, int> m;
        string ans;
        vector<int> v(n, 0);
        
        // Fill the frequency map and calculate future counts
        for (int i = n - 1; i >= 0; --i) {
            int t=m.size();
            if(m.find(s[i])!=m.end()) t=t-1;
            v[i] = t;
            m[s[i]]++;
        }
        
        int t = m.size() - 1;
        int c1 = -1;
        
        while (t >= 0) {
            char c = 'z' + 1; 
            for (int i = 0; i < n; ++i) {
                if (v[i] == t && s[i] < c && i > c1) {
                    c = s[i];
                    c1 = i;
                }
            }
            ans.push_back(c);
            
            // Find the last occurrence of the selected character
            int j = -1;
            for (int i = n - 1; i >= 0; --i) {
                if (s[i] == c) {
                    if(j==-1) j=i;
                    v[i]=-1;
                }
                else if(j!=-1 && i<j){
                    v[i]=v[i]-1;
                }
            }
           
            
        
            
            t--;
        }
        return ans;
    }
};
8600