lexical order

strings are compared from beginning to end. it’s not equal to sorted order.e.g. abc < acdb ==> smallest lexical order ~ get the smallest characters as early as possible

?? how to make optimal? if str[i] > str[i+1], delete str[i] will lead to optimal

class Solution:
# time O(N) space O(N)
    def removeDuplicateLetters(self, s: str) -> str:
        # initialize stack, seen set to make sure there is no duplicates, 
        # count number of each  charecter in the string
        counter,seen,stack = collections.Counter(s),set(),[]
        # cbacdcbc 
        for ch in s:
            # why counter here? make sure each letter will appear once instead of being remove in stack pop operation
            counter[ch] -= 1
            # avoid duplicate
            if ch in seen:
                continue
            # how to find smallest lexicographcal? get the smallesst alphabet as possible by comparing with top of stack for each charecter
            while stack and stack[-1] > ch and counter[stack[-1]] >0:
                # remove from seen set 
                seen.remove(stack.pop())
            stack.append(ch)
            seen.add(ch)
        return ''.join(stack)