Remove Duplicate Letters

Solution Code
class Solution:
    def removeDuplicateLetters(self, s: str) -> str:
        last_occ = {c: i for i, c in enumerate(s)}
        visited = set()
        stack = []
        
        for i, c in enumerate(s):
            if c in visited:
                continue
            
            while stack and c < stack[-1] and i < last_occ[stack[-1]]:
                visited.remove(stack.pop())
            
            visited.add(c)
            stack.append(c)
            
        return "".join(stack)

Time Complexity

O(N)

Space Complexity

O(1)