<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) {
        // Frequency map to count occurrences of each character in the string
        map<char, int> freq;
        // Map to check if a character is already in the current result
        map<char, bool> inResult;
        
        // Initialize frequency map
        for (char c : s) {
            freq[c]++;
        }
        
        string result = "";  // This will store the final result (like a stack)
        
        // Traverse each character in the string
        for (char c : s) {
            // Decrease the frequency of the current character
            freq[c]--;
            
            // If character is already in result, continue to the next character
            if (inResult[c]) continue;
            
            // While result is not empty, and the last character in the result is
            // lexicographically greater than the current character `c` and can appear later
            while (!result.empty() && result.back() > c && freq[result.back()] > 0) {
                // Remove the last character from result and mark it as not in the result
                inResult[result.back()] = false;
                result.pop_back();
            }
            
            // Add current character to the result and mark it as in the result
            result += c;
            inResult[c] = true;
        }
        
        return result;
    }
};

9200