<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:
    def removeDuplicateLetters(self, s: str) -> str:
        # Creating Map --> Char : Last Occuring Index
        char_last_occ_idx_map = {}
        for i in range(len(s)):
            char_last_occ_idx_map[s[i]] = i

        stack = []
        used = set() # Stores the Char's which are in Stack
        # Iterating through given String
        for i in range(len(s)):
            # If Current Char is already in Map,, then Continue
            if s[i] in used:
                continue

            # Popping Condition
            # If Cur. Char is Lesser than Top Char. of Stack && Top Char. has some remaining Occurences
            while stack and stack[-1] > s[i] and char_last_occ_idx_map[stack[-1]] > i :
                used.remove(stack[-1]) # Marking as UnVisited
                stack.pop() 
                
            # If Current Char. is Not Visited,, then Push
            if s[i] not in used:
                stack.append(s[i])
                used.add(s[i])
        
        return ''.join(stack)
16700