Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
Example 1:
Input: s = "bcabc"
Output: "abc"
Example 2:
Input: s = "cbacdcbc"
Output: "acdb"
Constraints:
1 <= s.length <= 104
s consists of lowercase English letters.
Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/
Problem summary: Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Stack · Greedy
Example 1
"bcabc"
Example 2
"cbacdcbc"
Related Problems
Smallest K-Length Subsequence With Occurrences of a Letter (smallest-k-length-subsequence-with-occurrences-of-a-letter)
Lexicographically Smallest String After Deleting Duplicate Characters (lexicographically-smallest-string-after-deleting-duplicate-characters)
Step 02
Core Insight
What unlocks the optimal approach
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #316: Remove Duplicate Letters
class Solution {
public String removeDuplicateLetters(String s) {
int n = s.length();
int[] last = new int[26];
for (int i = 0; i < n; ++i) {
last[s.charAt(i) - 'a'] = i;
}
Deque<Character> stk = new ArrayDeque<>();
int mask = 0;
for (int i = 0; i < n; ++i) {
char c = s.charAt(i);
if (((mask >> (c - 'a')) & 1) == 1) {
continue;
}
while (!stk.isEmpty() && stk.peek() > c && last[stk.peek() - 'a'] > i) {
mask ^= 1 << (stk.pop() - 'a');
}
stk.push(c);
mask |= 1 << (c - 'a');
}
StringBuilder ans = new StringBuilder();
for (char c : stk) {
ans.append(c);
}
return ans.reverse().toString();
}
}
// Accepted solution for LeetCode #316: Remove Duplicate Letters
func removeDuplicateLetters(s string) string {
last := make([]int, 26)
for i, c := range s {
last[c-'a'] = i
}
stk := []rune{}
vis := make([]bool, 128)
for i, c := range s {
if vis[c] {
continue
}
for len(stk) > 0 && stk[len(stk)-1] > c && last[stk[len(stk)-1]-'a'] > i {
vis[stk[len(stk)-1]] = false
stk = stk[:len(stk)-1]
}
stk = append(stk, c)
vis[c] = true
}
return string(stk)
}
# Accepted solution for LeetCode #316: Remove Duplicate Letters
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
last = {c: i for i, c in enumerate(s)}
stk = []
vis = set()
for i, c in enumerate(s):
if c in vis:
continue
while stk and stk[-1] > c and last[stk[-1]] > i:
vis.remove(stk.pop())
stk.append(c)
vis.add(c)
return ''.join(stk)
// Accepted solution for LeetCode #316: Remove Duplicate Letters
struct Solution;
impl Solution {
fn remove_duplicate_letters(text: String) -> String {
let mut stack: Vec<u8> = vec![];
let mut left: Vec<usize> = vec![0; 26];
for b in text.bytes() {
left[(b - b'a') as usize] += 1;
}
let mut visited: Vec<bool> = vec![false; 26];
for b in text.bytes() {
left[(b - b'a') as usize] -= 1;
if !visited[(b - b'a') as usize] {
visited[(b - b'a') as usize] = true;
while let Some(&top) = stack.last() {
if top > b && left[(top - b'a') as usize] > 0 {
visited[(top - b'a') as usize] = false;
stack.pop();
} else {
break;
}
}
stack.push(b);
}
}
stack.into_iter().map(|b| b as char).collect()
}
}
#[test]
fn test() {
let text = "cdadabcc".to_string();
let res = "adbc".to_string();
assert_eq!(Solution::remove_duplicate_letters(text), res);
let text = "abcd".to_string();
let res = "abcd".to_string();
assert_eq!(Solution::remove_duplicate_letters(text), res);
let text = "ecbacba".to_string();
let res = "eacb".to_string();
assert_eq!(Solution::remove_duplicate_letters(text), res);
let text = "leetcode".to_string();
let res = "letcod".to_string();
assert_eq!(Solution::remove_duplicate_letters(text), res);
}
// Accepted solution for LeetCode #316: Remove Duplicate Letters
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #316: Remove Duplicate Letters
// class Solution {
// public String removeDuplicateLetters(String s) {
// int n = s.length();
// int[] last = new int[26];
// for (int i = 0; i < n; ++i) {
// last[s.charAt(i) - 'a'] = i;
// }
// Deque<Character> stk = new ArrayDeque<>();
// int mask = 0;
// for (int i = 0; i < n; ++i) {
// char c = s.charAt(i);
// if (((mask >> (c - 'a')) & 1) == 1) {
// continue;
// }
// while (!stk.isEmpty() && stk.peek() > c && last[stk.peek() - 'a'] > i) {
// mask ^= 1 << (stk.pop() - 'a');
// }
// stk.push(c);
// mask |= 1 << (c - 'a');
// }
// StringBuilder ans = new StringBuilder();
// for (char c : stk) {
// ans.append(c);
// }
// return ans.reverse().toString();
// }
// }
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n)
Space
O(n)
Approach Breakdown
BRUTE FORCE
O(n²) time
O(1) space
For each element, scan left (or right) to find the next greater/smaller element. The inner scan can visit up to n elements per outer iteration, giving O(n²) total comparisons. No extra space needed beyond loop variables.
MONOTONIC STACK
O(n) time
O(n) space
Each element is pushed onto the stack at most once and popped at most once, giving 2n total operations = O(n). The stack itself holds at most n elements in the worst case. The key insight: amortized O(1) per element despite the inner while-loop.
Shortcut: Each element pushed once + popped once → O(n) amortized. The inner while-loop does not make it O(n²).
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
Breaking monotonic invariant
Wrong move: Pushing without popping stale elements invalidates next-greater/next-smaller logic.
Usually fails on: Indices point to blocked elements and outputs shift.
Fix: Pop while invariant is violated before pushing current element.
Using greedy without proof
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.