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.
1#include <stdio.h>
2#include <string.h>
3#include <stdbool.h>
4
5char* removeDuplicateLetters(char* s) {
6 int n = strlen(s);
7 int freq[26] = {0};
8 bool inStack[26] = {false};
9 for (int i = 0; i < n; i++) freq[s[i] - 'a']++;
10 char* stack = (char*)malloc((n + 1) * sizeof(char));
11 int top = -1;
12 for (int i = 0; i < n; i++) {
13 freq[s[i] - 'a']--;
14 if (inStack[s[i] - 'a']) continue;
15 while (top >= 0 && stack[top] > s[i] && freq[stack[top] - 'a'] > 0) {
16 inStack[stack[top] - 'a'] = false;
17 top--;
18 }
19 stack[++top] = s[i];
20 inStack[s[i] - 'a'] = true;
21 }
22 stack[++top] = '\0';
23 return stack;
24}
25
26int main() {
27 char s[] = "cbacdcbc";
28 printf("%s\n", removeDuplicateLetters(s));
29 return 0;
30}The code iterates through the string, keeping track of character frequencies and deciding whether to add each character to a stack based on lexicographical ordering and frequency constraints. Characters are popped from the stack if they have occurred later, are greater than the current character, and are not the last occurrence.
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
In this solution, a character set is updated via a general loop to progressively add elements to the result string. This method leverages frequency checks of character availability while ensuring characters are not redundant in the result.