## Algorithm

Problem Name: 316. Remove Duplicate Letters

Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is

among all possible results.

Example 1:

```Input: s = "bcabc"
Output: "abc"
```

Example 2:

```Input: s = "cbacdcbc"
Output: "acdb"
```

Constraints:

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

## Code Examples

### #1 Code Example with Java Programming

```Code - Java Programming```

``````
class Solution {
public String removeDuplicateLetters(String s) {
int[] counter = new int[26];
for (char c : s.toCharArray()) {
counter[c - 'a']++;
}
Stack stack = new Stack<>();
boolean[] visited = new boolean[26];
for (char c : s.toCharArray()) {
int idx = c - 'a';
counter[idx]--;
if (visited[idx]) {
continue;
}
while (!stack.isEmpty() && stack.peek() > idx && counter[stack.peek()] > 0) {
visited[stack.pop()] = false;
}
visited[idx] = true;
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) {
sb.append((char) (stack.pop() + 'a'));
}
return sb.reverse().toString();
}
}
``````
Copy The Code &

Input

cmd
s = "bcabc"

Output

cmd
"abc"

### #2 Code Example with Javascript Programming

```Code - Javascript Programming```

``````
const removeDuplicateLetters = function(s) {
const last = {}
for (let i = 0; i < s.length; i++) last[s.charAt(i)] = i
const stack = []
for (let i = 0; i < s.length; i++) {
const char = s.charAt(i)
while (stack.length && char < stack[0] && last[stack[0]] > i) {
stack.shift()
}
stack.unshift(char)
}
return stack.reverse().join('')
}
``````
Copy The Code &

Input

cmd
s = "bcabc"

Output

cmd
"abc"

### #3 Code Example with Python Programming

```Code - Python Programming```

``````
class Solution:
def removeDuplicateLetters(self, s):
rindex = {c: i for i, c in enumerate(s)}
result = ''
for i, c in enumerate(s):
if c not in result:
while c < result[-1:] and i < rindex[result[-1]]:
result = result[:-1]
result += c
return result
``````
Copy The Code &

Input

cmd
s = "cbacdcbc"

Output

cmd
"acdb"

### #4 Code Example with C# Programming

```Code - C# Programming```

``````
using System.Collections.Generic;

namespace LeetCode
{
public class _0316_RemoveDuplicateLetters
{
public string RemoveDuplicateLetters(string s)
{
var indexes = new Dictionary();
for (int i = 0; i < s.Length; i++)
indexes[s[i]] = i;

var seen = new HashSet();
var stack = new Stack();
for (int i = 0; i < s.Length; i++)
{
var ch = s[i];
if (!seen.Contains(ch))
{
while (stack.Count > 0 && stack.Peek() > ch && i < indexes[stack.Peek()])
seen.Remove(stack.Pop());

stack.Push(ch);
}
}

var str = new char[stack.Count];
int index = stack.Count - 1;
foreach (var ch in stack)
str[index--] = ch;
return new string(str);
}
}
}
``````
Copy The Code &

Input

cmd
s = "cbacdcbc"

Output

cmd
"acdb"