Remove Duplicate Letters solution explained
Remove Duplicate Letters asks for the alphabetically smallest string you can get by keeping exactly one copy of every distinct letter in the input while preserving their original order. The solution is a greedy stack: walk the string, skip letters already kept, and before pushing a letter pop any bigger letter on top that you know appears again later. With a table of each letter's last position it runs in O(n) time.
By Evin JohnPublished 7 min read
Restating the problem
You get a string of lowercase letters. Delete characters so that each letter that occurs in the string is left exactly once, and the survivors keep their original relative order. Among all strings you could end up with, return the one that comes first in dictionary order. The output always has the same length: the number of distinct letters in the input.
"dcadbc" -> "adbc" (the d before b must stay: no d appears after it)
"zyzxy" -> "yzx" (drop the first z and the last y)
"baab" -> "ab"
"edcba" -> "edcba" (every letter appears once, nothing to choose)
"aaaa" -> "a""dcadbc" is the instructive one. The best result would start "abcd", but the only d after the a sits before the b, and there is no later d to use instead, so "adbc" is the best you can do.
What it tests
This is a step up from plain monotonic stack problems because popping is not always allowed. You may only throw away a letter if a later copy can replace it, and you must not push a letter twice. Interviewers look for the moment you realize a simple "pop while bigger" breaks the rule that every letter must survive, and for how you fix it with one extra lookup.
Slow but sure: try every choice
Every valid answer picks one position for each distinct letter. For tiny inputs you can try every set of positions of the right size, keep the ones that use each letter once, and take the smallest. Since all candidates have the same length, Python's string comparison is the dictionary order the problem asks for.
from itertools import combinations
def remove_duplicate_letters_slow(s):
need = len(set(s))
best = None
for pos in combinations(range(len(s)), need):
cand = "".join(s[i] for i in pos)
if len(set(cand)) == need and (best is None or cand < best):
best = cand
return bestThe greedy stack
Build the answer left to right on a stack. When a new letter arrives, compare it with the top. If the top is bigger, the answer would be smaller with the new letter in that slot, but you can only remove the top if the same letter occurs again further right, so it can be added back later. That is what the last-position table answers in O(1). Keep popping while both conditions hold, then push the new letter.
One more rule: if the new letter is already on the stack, skip it. The copy on the stack sits further left and everything between it and the top is in increasing order or was forced to stay, so placing the letter again later can only make the result worse or invalid.
def remove_duplicate_letters(s):
last = {ch: i for i, ch in enumerate(s)}
stack, on_stack = [], set()
for i, ch in enumerate(s):
if ch in on_stack:
continue
while stack and stack[-1] > ch and last[stack[-1]] > i:
on_stack.remove(stack.pop())
stack.append(ch)
on_stack.add(ch)
return "".join(stack)function removeDuplicateLetters(s) {
const last = new Map();
for (let i = 0; i < s.length; i++) last.set(s[i], i);
const stack = [];
const onStack = new Set();
for (let i = 0; i < s.length; i++) {
const ch = s[i];
if (onStack.has(ch)) continue;
while (
stack.length &&
stack[stack.length - 1] > ch &&
last.get(stack[stack.length - 1]) > i
) {
onStack.delete(stack.pop());
}
stack.push(ch);
onStack.add(ch);
}
return stack.join("");
}Tracing "zyzxy"
| i | Letter | Action | Stack after |
|---|---|---|---|
| 0 | z | push | z |
| 1 | y | z > y and z appears at 2, pop z; push y | y |
| 2 | z | y < z, push | y z |
| 3 | x | z > x but last z was 2, cannot pop; push | y z x |
| 4 | y | already on the stack, skip | y z x |
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Try every set of positions | O(C(n, k) · k) | O(k) |
| Greedy stack with last positions | O(n): each letter pushed and popped at most once | O(k) for the stack, set and table |
Inputs that catch bugs
- A single letter, or one letter repeated: the answer is that letter.
- No repeats at all, like "edcba": nothing can be popped, because no letter appears again.
- Strictly rising input: every letter is pushed and none is popped.
- A bigger letter whose last copy comes before a smaller one, like the d in "dcadbc".
- A repeat of a letter already on the stack, like the last y in "zyzxy": it must be skipped, not pushed.
Common mistakes
- Popping without checking the last position, which can drop a letter forever and return a string that is missing it.
- Forgetting the used set, so a letter ends up on the stack twice.
- Removing a popped letter from the stack but not from the used set, so its later copy is wrongly skipped.
- In the version that counts remaining copies instead of storing last positions, lowering the count only after the skip check. A skipped letter still uses up one copy, so decrement first.
- Sorting the distinct letters, which ignores the order rule entirely.
Variations
- Smallest subsequence of distinct characters: the same task under another name; the code is identical.
- Largest result instead of smallest: flip the comparison so you pop smaller letters.
- Exactly k removals with no distinct-letter rule: the simpler Remove K Digits, where you pop freely while removals remain.
- Each letter kept at most twice: count remaining copies instead of storing the last position, and pop only while the count after this point is high enough.
How to explain it out loud
Fictional example
- Candidate
- I want the smallest string in dictionary order, so I want small letters as early as possible. That suggests a stack where I pop bigger letters when a smaller one arrives.
- Candidate
- But I cannot pop a letter if this was its last copy, or it would be missing from the answer. So I precompute each letter's last index and only pop when the top appears again later.
- Interviewer
- What happens when you see a letter that is already in your answer?
- Candidate
- I skip it. The earlier copy is already placed in the best spot the constraints allowed. Each letter is pushed and popped at most once, so the pass is linear.
Related problems
Remove K Digits, linked above, is the version without the survival rule. In this batch, Validate Stack Sequences simulates a stack under a fixed pop order, and Score of Parentheses uses a stack to evaluate nested structure. For another monotonic stack, see Next Greater Element.
Practicing with Natively
The hard part of this problem is spotting the condition on the pop, and that is easier to catch when you say your plan aloud. In a practice session Natively, on Mac or Windows, can read the prompt from a screenshot, hint at the last-index table if you are stuck on the plain stack, and transcribe your explanation so you can check whether you justified the skip rule or only stated it. The LeetCode practice page describes how that works.
Questions people ask
How do you solve Remove Duplicate Letters?
Record each letter's last index. Walk the string with a stack, skip letters already on it, and before pushing pop any bigger top letter that appears again later. The stack is the answer.
Why do you need the last index of each letter?
You may only remove a letter from the stack if a later copy can take its place. The last index tells you in constant time whether that copy exists.
What is the time complexity of Remove Duplicate Letters?
O(n), because each letter is pushed and popped at most once. Extra space is proportional to the number of distinct letters.
Is Remove Duplicate Letters the same as Smallest Subsequence of Distinct Characters?
Yes. Both ask for the smallest result in dictionary order that keeps each distinct letter once in original order, and the same code solves both.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
