Skip to content

316. Remove Duplicate Letters

Difficulty Topics

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 <= 104
  • s consists of lowercase English letters.

 

Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/

Solution

remove-duplicate-letters.py
class Solution:
    def removeDuplicateLetters(self, s: str) -> str:
        counter = Counter(s)
        stack = []
        put = set()

        for x in s:
            counter[x] -= 1

            if x in put: continue

            while stack and x < stack[-1] and counter[stack[-1]] > 0:
                put.remove(stack.pop())

            stack.append(x)
            put.add(x)

        return "".join(stack)