<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 size = s.size();
        int lptr = 0, rptr = 0;

        // vector for character last occu
        vector<int> charLastOcc(26, 0);
        for (int i = 0; i < size; i++) {
            charLastOcc[s[i] - 'a'] = i;
        }

        // vector for character pres.
        vector<bool> charPres(26, false);

        string finalStr;

        // traverse through the array
        for (int letter = 0; letter < size; letter++) {

            // check if char previously visited
            if (charPres[s[letter] - 'a'] == true) {
                continue;
            } else {
                // incase string is empty continue wiht process and mark true
                if (finalStr.empty()) {
                    finalStr.push_back(s[letter]);
                    charPres[s[letter] - 'a'] = true;
                } else {
                    // check lexi. order
                    while (!finalStr.empty() && s[letter] < finalStr.back()) {

                        // check if last time character occured is later than
                        // curr or not
                        if ( !finalStr.empty() && charLastOcc[finalStr.back() - 'a'] > letter) {

                            // if so mark false and remove
                            charPres[finalStr.back() - 'a'] = false;
                            finalStr.pop_back();
                        } else
                            break;
                    }
                    finalStr.push_back(s[letter]);
                    charPres[s[letter] - 'a'] = true;
                }
            }
        }
        return finalStr;
    }
};

8400