316. Remove Duplicate Letters
Asked at 13Amazon38Microsoft35Google33Bloomberg32Meta22Paytm79TikTok58FactSet100ByteDance87Expedia84Nutanix60Zoho42DE Shaw38
Problem
Remove letters from s so that every distinct letter appears exactly once, and return the lexicographically smallest such result (letters keep their relative order).
Example: "bcabc" → "abc"; "cbacdcbc" → "acdb"
Smallest lexicographic result with each letter once. Keep an increasing stack; pop the top if it's larger than the current letter and appears again later (we can re-add it). Skip letters already in the stack.
Complexity: O(n).
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
last = {ch: i for i, ch in enumerate(s)}
st, used = [], set()
for i, ch in enumerate(s):
if ch in used:
continue
while st and st[-1] > ch and last[st[-1]] > i:
used.remove(st.pop())
st.append(ch)
used.add(ch)
return "".join(st)
assert Solution().removeDuplicateLetters("bcabc") == "abc"
assert Solution().removeDuplicateLetters("cbacdcbc") == "acdb"
class Solution {
public String removeDuplicateLetters(String s) {
int[] last = new int[26];
for (int i = 0; i < s.length(); i++) last[s.charAt(i) - 'a'] = i;
boolean[] used = new boolean[26];
StringBuilder st = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (used[c - 'a']) continue;
while (st.length() > 0 && st.charAt(st.length() - 1) > c && last[st.charAt(st.length() - 1) - 'a'] > i) {
used[st.charAt(st.length() - 1) - 'a'] = false;
st.deleteCharAt(st.length() - 1);
}
st.append(c);
used[c - 'a'] = true;
}
return st.toString();
}
}
func removeDuplicateLetters(s string) string {
var last [26]int
for i := 0; i < len(s); i++ {
last[s[i]-'a'] = i
}
var used [26]bool
st := []byte{}
for i := 0; i < len(s); i++ {
ch := s[i]
if used[ch-'a'] {
continue
}
// pop bigger letters that appear again later
for len(st) > 0 && st[len(st)-1] > ch && last[st[len(st)-1]-'a'] > i {
used[st[len(st)-1]-'a'] = false
st = st[:len(st)-1]
}
st = append(st, ch)
used[ch-'a'] = true
}
return string(st)
}