MediumStringStackGreedyMonotonic Stack

Remove Duplicate Letters

LeetCode
1 approach, code in all languages

You are given a string `s`. Remove duplicate letters so that every letter appears exactly once in the result.

Among all valid results, return the one that is the smallest in lexicographic order. The relative order of the letters you keep must match their order in the original string.

Example 1

Input: s = "bcabc"

Output: "abc"

Each of a, b, and c appears once, and abc is the lexicographically smallest arrangement achievable while preserving order.

Example 2

Input: s = "cbacdcbc"

Output: "acdb"

Dropping the earlier b and c in favor of later occurrences yields acdb, which is smaller than any other valid single-copy ordering.

Constraints

  • 1 <= s.length <= 10^4
  • s consists of lowercase English letters.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now