Remove Duplicate Letters in Lexicographic Order

Implement removeDuplicateLettersLex

Given a lowercase string s, remove duplicate letters so every letter appears exactly once in the result, keeping the relative order of the letters you keep — and among every arrangement that satisfies those two rules, return the lexicographically smallest one. The greedy rule: a character should give way to a later, smaller character only if it's guaranteed to reappear afterward — otherwise removing it loses that letter from the answer entirely. A single pass with a stack applies this rule the instant each character arrives: pop anything bigger off the top as long as a precomputed "last occurrence" table confirms it will show up again later, then push the new character (skipping it entirely if it's already on the stack). That's the same decision the brute force's recursive "find the safe cutoff, then rebuild" approach makes — just recognized immediately instead of rediscovered by rescanning from scratch after every pick.

Example 1:

Input: s = "dfaedbef"

Output: "adbef"

Example 2:

Input: s = "rspqrs"

Output: "pqrs"

Example 3:

Input: s = "mississippi"

Output: "misp"

+ 3 hidden test cases run on Submit.

Constraints:

  • 1 ≤ s.length ≤ 15
  • s consists only of lowercase English letters

s =

dfaedbef