Remove Duplicate Letters

Given a string `s`, remove duplicate letters so that every letter appears once and only once. Among all possible results, return the one that is smallest in lexicographical order. The letters you keep must stay in their original relative order.

30:00

Remove Duplicate Letters
medium
Free written solution
Topics
Companies

Given a string s, remove duplicate letters so that every letter appears once and only once. Among all possible results, return the one that is smallest in lexicographical order. The letters you keep must stay in their original relative order.

Example 1:
Input: {"s":"bcabc"}
Output: abc
Constraints:
  • 1≤s.length≤1041 \leq \text{s.length} \leq 10^4

  • s consists of lowercase English letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"bcabc"}

s (5 letters)

underlined = last copy of that letter

b

0

c

1

a

2

b

3

c

4

First record where each letter appears for the last time (a→2, b→3, c→4). A letter can only be put off while a later copy exists.

stack (bottom → top) = answer so far

size 0

empty

on stack:

a
b
c
Variables
VariableValue
stack""
DepthFunction Call
Stack empty
0/19