Problem 316

Abstract / Summary

Given a string keep only the first occurrence of each letter and make the result smallest in alphabetical order.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0316.py

class Solution:
    def removeDuplicateLetters(self, s: str) -> str:
        # idea: try to ensure s[i] < s[i+1]
        #       unless s[i] is the rightmost location of its letter
        freq = defaultdict(int)
        for c in s:
            freq[c] += 1

        result = ""
        for c in s:
            freq[c] -= 1
            if c in result:
                continue

            # remove last if lexicographically bigger
            while len(result) > 0 and c < result[-1]:
                # but not if the last of its kind
                if freq[result[-1]] == 0:
                    break
                result = result[:-1]

            result += c

        return result
24 lines | 713 bytes | submitted September 9, 2023 | GitHub   25% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 54% (800k+ submissions).

Typical patterns to solve this problem:
  • Greedy
  • Monotonic Stack
  • Stack
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the classic “remove duplicate letters” problem by constructing the smallest lexicographic string that contains each character of the input exactly once. It proceeds in a single pass while maintaining a frequency map of remaining characters and a mutable result string that behaves like a stack. The algorithm guarantees that the final string respects the required ordering constraints without revisiting characters.

Key Steps

Building the frequency table

The first loop iterates over the input string and records how many times each character appears. This table is later consulted to decide whether a character that currently sits at the end of the result can be safely discarded.

freq = defaultdict(int)
for c in s:
    freq[c] += 1

Iterating through the input

A second pass processes each character in order. For every character the algorithm decrements its remaining count, then checks whether it already exists in the result. If it does, the character is ignored because the result already contains the required single occurrence.

for c in s:
    freq[c] -= 1
    if c in result:
        continue

Maintaining lexicographic minimality

When a new character is not yet in the result, the algorithm attempts to pop larger characters from the end of the result. The while-loop continues as long as the last character of the result is lexicographically greater than the current character and there is at least one more occurrence of that last character later in the string (as indicated by a non-zero frequency). This ensures that removing the larger character will not prevent it from appearing later, thereby preserving the ability to include every distinct letter.

while len(result) > 0 and c < result[-1]:
    if freq[result[-1]] == 0:
        break
    result = result[:-1]

Adding the current character

After any necessary removals, the current character is appended to the result, effectively pushing it onto the stack.

result += c

Returning the final string

When the loop finishes, the result string contains each distinct character exactly once, ordered to be the smallest possible lexicographically.

return result

Edge Cases Handled

The algorithm gracefully handles strings that consist of a single repeated character. In such a case the frequency table records the count, the first occurrence is added to the result, and all subsequent occurrences are skipped because the character is already present.

When the input is already in strictly increasing lexicographic order, the while-loop never triggers, and the result is simply the original string without duplicates.

If the input contains characters that appear only once, the condition freq[result[-1]] == 0 prevents their removal, guaranteeing that essential characters are never discarded even if a smaller character follows them.

The code also works correctly for strings that contain all 26 lowercase letters in random order, ensuring each letter appears exactly once in the final output.

Performance Optimizations

The solution uses a dictionary (defaultdict) for constant-time frequency updates and lookups, avoiding the overhead of repeated scans. By treating the result string as a mutable stack and performing slice operations (result = result[:-1]) only when necessary, the algorithm minimizes the number of string reallocations. The overall design ensures that each character is pushed onto the result at most once and popped at most once, leading to linear work relative to the length of the input. The early continue for already-seen characters prevents unnecessary processing, further reducing the number of iterations inside the inner while-loop.

written by openai gpt

ELI5 - Simplified Explanation

Imagine playing a game where you have a line of alphabet blocks and you want to make a special pile that uses one of each letter. You want to pick the letters in an order that keeps everything nice and alphabetical, like the way books are organized on a shelf.

The code first looks at all the blocks to see how many of each letter are waiting in line. As it walks down the line, it keeps a count of how many blocks of each kind are left to see.

When it picks up a letter, it checks if it already has that letter in its pile. If the letter is already there, it just skips it because there is no need to pick it up twice.

If the new letter comes before the last letter added to the pile in the alphabet, the code thinks about swapping them to keep things in better order. It looks at the last letter in the pile and asks if there are any more of those blocks left further down the line. If there are more of those blocks waiting ahead, it takes the last one out of the pile so it can put the new, better letter in its place. If there are no more of those blocks left, it keeps the block in the pile because it cannot find another one later.

It keeps doing this until it has gone through all the blocks in the line, resulting in a neat pile with each letter appearing just once in the best possible order.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.93 | σ = 1.61

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
fpdjsns C++
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
MacJim C++
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
XiaotaoGuo C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
fpdjsns C++
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
MacJim C++
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
XiaotaoGuo C++
zfang399 C++
39 links | 26 authors | 9 languages

Videos

11 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

1 easy 3 medium 1 hard
6 solutions   September 9, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality