Remove Duplicate Letters — LeetCode 316 Python Solution
MediumStackGreedyStringMonotonic Stack
- Problem
- #316
- Pattern
- Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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
- Input
- s = "bcabc"
- Output
- "abc"
Python solution
Python
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)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 316. Remove Duplicate Letters is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 316. Remove Duplicate Letters?
- LeetCode 316. Remove Duplicate Letters is rated Medium on LeetCode.
- What is the time complexity of LeetCode 316. Remove Duplicate Letters?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 316. Remove Duplicate Letters?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 316. Remove Duplicate Letters cover?
- LeetCode 316. Remove Duplicate Letters is tagged Stack, Greedy, String and Monotonic Stack on LeetCode.