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

Code 1: O(n)

``````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)

``````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();
}
}
``````