Remove Duplicate Letters

Given a string s, remove duplicate letters so that every letter appears once and only once and the resulting string is the smallest in lexicographical order among all possible results. Pattern focus: Local Choice Proof. Keep the smallest possible character at each step while ensuring every character can still appear later; a monotonic stack with last occurrence tracking is the standard approach.

Input Format

s = input string

Output Format

lexicographically smallest unique-letter string

Constraints

  • 1 <= s.length <= 10^5
  • s consists of lowercase English letters

Examples

Example 1:

Input:

s = "bcabc"

Output:

abc

Explanation:

Removing duplicates while preserving order constraints yields the smallest unique string.

Example 2:

Input:

s = "cbacdcbc"

Output:

acdb

Explanation:

The correct answer keeps the lexicographically smallest valid subsequence.

Example 3:

Input:

s = "abacb"

Output:

abc

Explanation:

Choosing the smallest valid subsequence gives 'abc'.

Loading...
Remove Duplicate Letters - Greedy DSA Problem