Skip to content

316. Remove Duplicate Letters

String Stack Greedy Monotonic Stack

Problem - Remove Duplicate Letters

Medium

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/

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
    def removeDuplicateLetters(self, s: str) -> str:
        last_map = {val : i for i, val in enumerate(s)}
        stack = []
        vals = set()

        for i, ch in enumerate(s):
            if ch in vals:
                continue
            while stack and stack[-1] > ch and last_map[stack[-1]] > i:
                vals.remove(stack.pop())
            stack.append(ch)
            vals.add(ch)
        return "".join(stack)

Submission Stats:

  • Runtime: 0 ms (100.00%)
  • Memory: 17.8 MB (46.70%)