MediumNo. 1081
Smallest Subsequence of Distinct Characters — LeetCode 1081 Python Solution
- Pattern
- Stack
- Topics
- Stack, Greedy, String, Monotonic Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a string s, return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once.
Example
- Input
- s = "bcabc"
- Output
- "abc"
Python solution
class Solution:
def smallestSubsequence(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
- Time
- O(n log n)
- Space · auxiliary
- O(1) to O(n)
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1081. Smallest Subsequence of Distinct Characters 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
| No. | Problem | Difficulty |
|---|---|---|
| 0316 | Remove Duplicate Letters | Medium |
| 0402 | Remove K Digits | Medium |
| 0768 | Max Chunks To Make Sorted II | Hard |
| 0769 | Max Chunks To Make Sorted | Medium |
| 0921 | Minimum Add to Make Parentheses Valid | Medium |
| 0936 | Stamping The Sequence | Hard |
Frequently asked questions
- How hard is LeetCode 1081. Smallest Subsequence of Distinct Characters?
LeetCode 1081. Smallest Subsequence of Distinct Characters is rated Medium on LeetCode.
- What topics does LeetCode 1081. Smallest Subsequence of Distinct Characters cover?
LeetCode 1081. Smallest Subsequence of Distinct Characters is tagged Stack, Greedy, String and Monotonic Stack on LeetCode.