> For the complete documentation index, see [llms.txt](https://code-snippets.hbamithkumara.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://code-snippets.hbamithkumara.com/leetcode/problems/301-400/remove-duplicate-letters.md).

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

*
