Remove Duplicate Letters
Problem Statement
You are given a string s of lowercase letters.
Remove letters so that every distinct letter appears exactly once. The letters you keep stay in their original order (you are choosing a subsequence).
Among all the ways to do that, return the one that is smallest in dictionary order.
(LeetCode 1081, Smallest Subsequence of Distinct Characters, is the same problem.)
A string s of lowercase English letters.
The smallest subsequence of s (in dictionary order) that contains each distinct letter of s exactly once.
The letters are a, b, c. Keep the a at index 2 and the b, c after it.
Keep the a (index 2), c (3), d (4) and b (6). Something smaller like "abcd" or "acbd" is impossible: the only d is at index 4, and no b sits between the a and that d, so the b has to come after the d.
- • 1 ≤ s.length ≤ 10^4
- • `s` has only lowercase English letters
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Generate every subsequence with each letter once; keep the smallest
Pick the smallest letter that still leaves every other needed letter later; repeat
Skip letters already used; pop a bigger top only if it appears again later; push
For each position, either keep the letter or skip it, but never keep a letter twice. When you reach the end, the result counts only if it has every distinct letter. Keep the smallest one you find.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Monotonic Stack translate into production architectures and low-level memory mechanics.