> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Remove Duplicate Letters Python Solution

> Tested Python solution for LeetCode 316 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 316, [Medium](/catalog/medium). Topics: [String](/catalog/topics/string), [Stack](/catalog/topics/stack), [Greedy](/catalog/topics/greedy), [Monotonic Stack](/catalog/topics/monotonic-stack). [View on LeetCode](https://leetcode.com/problems/remove-duplicate-letters/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 316   # by problem number
lcpy gen -s remove_duplicate_letters   # by problem name
```

## 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.

### Examples

```
Input: s = "bcabc"
Output: "abc"
Explanation: The possible results are "abc", "bac", "bca", "cab", and "cba". The smallest is "abc".
```

```
Input: s = "cbacdcbc"
Output: "acdb"
Explanation: Removing duplicates while keeping the result smallest gives "acdb".
```

### Constraints

* `1 <= s.length <= 10^4`
* `s` consists of lowercase English letters.

**Note:** This question is the same as 1081: [Smallest Subsequence of Distinct Characters](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/).

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/remove_duplicate_letters/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/remove_duplicate_letters/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n) - each character is pushed and popped at most once
    # Space: O(k) - stack and membership set hold at most k distinct letters (k <= 26)
    def remove_duplicate_letters(self, s: str) -> str:
        last_index = {char: i for i, char in enumerate(s)}
        stack: list[str] = []
        in_stack: set[str] = set()

        for i, char in enumerate(s):
            if char in in_stack:
                continue
            while stack and stack[-1] > char and last_index[stack[-1]] > i:
                in_stack.remove(stack.pop())
            stack.append(char)
            in_stack.add(char)

        return "".join(stack)
```

## Complexity

| Time | Space |
| - | - |
| O(n) - each character is pushed and popped at most once | O(k) - stack and membership set hold at most k distinct letters (k \<= 26) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.