[LeetCode] Lexicographically Smallest String After Deleting Duplicate Characters

3816. Lexicographically Smallest String After Deleting Duplicate Characters

You are given a string s that consists of lowercase English letters.

You can perform the following operation any number of times (possibly zero times):

  • Choose any letter that appears at least twice in the current string s and delete any one occurrence.

Return the lexicographically smallest resulting string that can be formed this way.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
string lexSmallestAfterDeletion(string s) {
unordered_map<char,int> freq;
for(auto& ch : s) freq[ch]++;
for(char ch = 'a'; ch <= 'z'; ch++) {
string ss = "";
for(auto& now : s) {
while(ss.size() and ss.back() > now and freq[ss.back()] >= 2) {
freq[ss.back()]--;
ss.pop_back();
}
ss.push_back(now);
}
swap(ss,s);
}
while(s.size() and freq[s.back()] >= 2) {
freq[s.back()]--;
s.pop_back();
}
return s;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/lexicographically-smallest-string-after-deleting-duplicate-characters/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.