<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) {
        vector<bool> seen(26, false); // track visited characters
        vector<int> lastIndex(26, 0); // store last index of each character
        string result = "";           // use the result string as a stack

        for (int i = 0; i < s.length(); i++) {
            lastIndex[s[i] - 'a'] = i;
        }

        for (int i = 0; i < s.length(); i++) {
            char currentChar = s[i];
            if (seen[currentChar - 'a']) {
                continue; // skip if already in the result
            }

            // pop characters from the result string (acting like a stack)
            while (!result.empty() && currentChar < result.back() && i < lastIndex[result.back() - 'a']) {
                seen[result.back() - 'a'] = false; // mark as unvisited
                result.pop_back(); 
            }

            result.push_back(currentChar); // add the current character 
            seen[currentChar - 'a'] = true; // mark as visited
        }

        return result;
    }
};
8200