Description
Given a string s, return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once.
Example 1:
Input: s = "bcabc" Output: "abc"
Example 2:
Input: s = "cbacdcbc" Output: "acdb"
Constraints:
1 <= s.length <= 1000sconsists of lowercase English letters.
Note: This question is the same as 316: https://leetcode.com/problems/remove-duplicate-letters/
Solutions
Based on editorial's strategy.
Language: javascript(2026-07-19 09:34)DONE
CPU Performance59.18%
Memory Performance59.18%
/**
* @param {string} s
* @return {string}
*/
var smallestSubsequence = function(s) {
const freq = Array(26).fill(0);
for (let i = 0; i < s.length; i++) {
const pos = s.charCodeAt(i) - 97;
freq[pos]++;
}
const seen = Array(26).fill(false);
const stack = [];
for (let i = 0; i < s.length; i++) {
const pos = s.charCodeAt(i) - 97;
if (!seen[pos]) {
while (stack[stack.length - 1] > s[i] && freq[stack[stack.length - 1].charCodeAt(0) - 97] > 0) {
seen[stack[stack.length - 1].charCodeAt(0) - 97] = false;
stack.pop();
}
seen[pos] = true;
stack.push(s[i]);
}
freq[pos]--;
}
return stack.join('');
};