# 316. Remove Duplicate Letters

Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

**Example 1:**

```
Input:
"bcabc"
Output:
"abc"
```

**Example 2:**

```
Input:
"cbacdcbc"
Output:
"acdb"
```

**Thoughts**

1. Greedy: In the search space of i to j where the last character in s\[i...j] in also of its last appearance of the whole string s, find the small character in lexicographical order, delete it in the subsequent substring and then perform the search starting from j + 1.
2. Using stack:&#x20;
   1. Count the letter frequency with an Array
   2. Build a ascending stack: Each time adding a letter to the stack if it has not been added into the stack, mark letter as **visited**. If current letter is smaller than the that on top of the stack, **and** top letter has remaining appearance after (as checked by indexing the letter frequency array), pop the letter out and mark it as **not visited**&#x20;

**Code 1: O(n)**

```java
class Solution {
    public String removeDuplicateLetters(String s) {
        int [] cnt = new int [26];
        for (int i = 0; i < s.length(); i++){
            cnt[s.charAt(i) - 'a']++;
        }

        int pos = 0;
        for(int i = 0; i < s.length(); i++){
            if(s.charAt(pos) > s.charAt(i)) pos = i;
            if (--cnt[s.charAt(i) - 'a'] == 0) break;
        }

        return s.length() == 0 ? "": s.charAt(pos) + removeDuplicateLetters(s.substring(pos + 1).replaceAll("" + s.charAt(pos), ""));
    }
}
```

**Code 2 : O(n)**&#x20;

```java
class Solution {
    public String removeDuplicateLetters(String s) {
        int [] res = new int[26];
        boolean [] vis = new boolean [26];
        char[] chars = s.toCharArray();
        Stack<Character> st = new Stack<>();
        for(char c: chars){
            res[c - 'a']++;
        }
        int index = -1;
        for (char c: chars){
            index = c - 'a';
            res[index] --;
            if (vis[index])
                continue;
            while (!st.isEmpty() && c < st.peek() && res[st.peek() - 'a']!= 0){
                char top = st.pop();
                vis[top - 'a'] = false;
            }
            st.push(c);
            vis[index] = true;

        }

        StringBuilder sb = new StringBuilder();
        while (!st.isEmpty()){
            sb.insert(0, st.pop());
        }
        return sb.toString();
    }
}
```


---

# 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.taozirui.com/lc/data-structure/stack/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.
