This approach uses a stack to build the resultant string such that it is the smallest lexicographical order. We will also use an array to keep count of each character’s frequency and a boolean array to track the characters that have been added to the stack. As we iterate over each character, we decide whether to add it to the stack or skip it based on the frequency and lexicographical conditions.
Time Complexity: O(n), where n is the length of the string, as each character is pushed and popped from the stack at most once.
Space Complexity: O(1), because the stack contains at most 26 characters, and other auxiliary data structures are of constant size.
1function removeDuplicateLetters(s) {
2 const freq = new Array(26).fill(0);
3 const inStack = new Array(26).fill(false);
4 for (let char of s) {
5 freq[char.charCodeAt(0) - 'a'.charCodeAt(0)]++;
6 }
7 const stack = [];
8 for (let char of s) {
9 freq[char.charCodeAt(0) - 'a'.charCodeAt(0)]--;
10 if (inStack[char.charCodeAt(0) - 'a'.charCodeAt(0)]) continue;
11 while (stack.length > 0 && stack[stack.length - 1] > char && freq[stack[stack.length - 1].charCodeAt(0) - 'a'.charCodeAt(0)] > 0) {
12 inStack[stack.pop().charCodeAt(0) - 'a'.charCodeAt(0)] = false;
13 }
14 stack.push(char);
15 inStack[char.charCodeAt(0) - 'a'.charCodeAt(0)] = true;
16 }
17 return stack.join('');
18}
19
20console.log(removeDuplicateLetters("cbacdcbc"));In the JavaScript solution, the use of array to track frequency and presence of a character builds the answer via stack for ensuring lexicographical minimality. It iterates over the string while maintaining a character stack from which elements are both added and removed.
This approach focuses on iteratively constructing the result string while ensuring that the result remains lexicographically smallest by checking each character and including it in the result only if it meets certain frequency and order criteria.
Time Complexity: O(n), where n is the length of the input string.
Space Complexity: O(1), considering character storage is bounded to a maximum of 26.
1
This Java solution repeatedly reevaluates whether to add each element into the result string itself, improving space performance vis-à-vis comparative approach and efficiency via, minimal edits required powers practical solution implementation.