All problems
0366MediumStringStackGreedyMonotonic Stack

Smallest Distinct Label

Tracked in this browser only
Write code

Trains the technique from

LeetCode 316Remove Duplicate Letters

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A catalogue folds a raw code s of lowercase letters down to a label.

The label has to hold every distinct letter of s exactly once, and it has to be reachable from s by deleting characters only, so the letters that survive stay in the order they had in s.

More than one label can meet both rules. Return the one that comes first in dictionary order.

Examples

Example 1

Input
s = "dbacdb"
Output
"acdb"

The distinct letters are a, b, c and d. Deleting positions 0, 1 and 5 of "dbacdb" leaves "acdb", which holds each of them once.

Example 2

Input
s = "ba"
Output
"ba"

Both letters have to appear, and the only way to keep them in their original order is "ba".

Example 3

Input
s = "zzzz"
Output
"z"

Only the letter z occurs, so the label is a single z.

Example 4

Input
s = "bcac"
Output
"bac"

Deleting the c at position 1 leaves "bac", which holds a, b and c once each.

Constraints

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

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def remove_duplicate_letters(s: str) -> str:
Java
public String removeDuplicateLetters(String s)
September 7
Apply