Remove Duplicate Letters — LeetCode 316 Python Solution

MediumStackGreedyStringMonotonic Stack
Problem
#316
Pattern
Stack
Reading time
2 min

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

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

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