Smallest Subsequence of Distinct Characters — LeetCode 1081 Python Solution
MediumStackGreedyStringMonotonic Stack
- Problem
- #1081
- Pattern
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n log n) |
| Space | O(1) to O(n) auxiliary |
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
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.