Remove Duplicate Letters

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Given a string s, remove duplicate letters so that every letter appears once and only once. Return the result that is the smallest in lexicographical order among all possible results.

Examples

Example 1:

Input: s = "bcabc"

Output: "abc"

Explanation: The unique letters are a, b, and c. The smallest lexicographical ordering using each letter once is "abc".

Example 2:

Input: s = "cbacdcbc"

Output: "acdb"

Explanation: The result must contain each of a, b, c, d exactly once. "acdb" is the smallest lexicographical result achievable while respecting the relative order constraint.

Example 3:

Input: s = "abacb"

Output: "abc"

Explanation: Removing duplicates while maintaining the smallest lexicographical order gives "abc".

Constraints

  • 1 <= s.length <= 10⁴
  • s consists of lowercase English letters.
Source: Monotonic Stack pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle