Description
Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
Β
Example 1:
Input: s = "bcabc" Output: "abc"
Example 2:
Input: s = "cbacdcbc" Output: "acdb"
Β
Constraints:
1 <= s.length <= 104sconsists of lowercase English letters.
Β
Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/
Solution
Python3
class Solution:
    def removeDuplicateLetters(self, s: str) -> str:
        count = Counter(s)
        stack = []
        put = set()
 
        for i, x in enumerate(s):
            count[x] -= 1
            if x in put: continue
 
            while stack and x < stack[-1] and count[stack[-1]] > 0:
                put.remove(stack.pop())
            
            stack.append(x)
            put.add(x)
 
        return "".join(stack)