Smallest Subsequence of Distinct Characters — LeetCode 1081 Python Solution

MediumStackGreedyStringMonotonic Stack
Problem
#1081
Pattern
Stack
Reading time
2 min

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

MeasureComplexity
TimeO(n log n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview