SDE & MLE Prep

316. Remove Duplicate Letters

Problem

Remove letters from s so that every distinct letter appears exactly once, and return the lexicographically smallest such result (letters keep their relative order).

Example: "bcabc" → "abc"; "cbacdcbc" → "acdb"

Smallest lexicographic result with each letter once. Keep an increasing stack; pop the top if it's larger than the current letter and appears again later (we can re-add it). Skip letters already in the stack.

Complexity: O(n).

class Solution:
    def removeDuplicateLetters(self, s: str) -> str:
        last = {ch: i for i, ch in enumerate(s)}
        st, used = [], set()
        for i, ch in enumerate(s):
            if ch in used:
                continue
            while st and st[-1] > ch and last[st[-1]] > i:
                used.remove(st.pop())
            st.append(ch)
            used.add(ch)
        return "".join(st)