# 316. Remove Duplicate Letters

### Description

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.

**Note:** This question is the same as 1081: <https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/>

### Constraints

* `1 <= s.length <= 104`
* `s` consists of lowercase English letters.

### Approach

### Links

* GeeksforGeeks
* [Leetcode](https://leetcode.com/problems/remove-duplicate-letters/)
* ProgramCreek
* YouTube

### **Examples**

{% tabs %}
{% tab title="Example 1" %}
**Input:** s = "bcabc"

**Output:** "abc"
{% endtab %}

{% tab title="Example 2" %}
**Input:** s = "cbacdcbc"

**Output:** "acdb"
{% endtab %}
{% endtabs %}

### **Solutions**

{% tabs %}
{% tab title="Solution 1" %}

```java
/**
 * Time complexity : 
 * Space complexity : 
 */

class Solution {
    public String removeDuplicateLetters(String s) {
        if(s == null || s.length() == 0) return "";
        
        int[] count = new int[128];
        char[] result = new char[26];
        boolean[] assigned = new boolean[128];
        
        int sLen = s.length();
        
        for(int i = 0; i < sLen; i++) {
            count[s.charAt(i)]++;
        }
        
        char ch;
        int end = -1;
        
        for(int i = 0; i < sLen; i++) {
            ch = s.charAt(i);
            count[ch]--;
            
            if(assigned[ch]) continue;
            
            while(end >= 0 && result[end] > ch && count[result[end]] > 0) {
                assigned[result[end]] = false;
                end--;
            }
            
            end++;
            result[end] = ch;
            assigned[ch] = true;
        }
        
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i <= end; i++) {
            sb.append(result[i]);
        }
        
        return sb.toString();
    }
}
```

{% endtab %}
{% endtabs %}

### **Follow up**

*


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://code-snippets.hbamithkumara.com/leetcode/problems/301-400/remove-duplicate-letters.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
