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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public string RemoveDuplicateLetters(string s) {
6 int[] freq = new int[26];
7 bool[] inStack = new bool[26];
8 foreach (char c in s) freq[c - 'a']++;
9 Stack<char> stack = new Stack<char>();
10 foreach (char c in s) {
11 freq[c - 'a']--;
12 if (inStack[c - 'a']) continue;
13 while (stack.Count > 0 && stack.Peek() > c && freq[stack.Peek() - 'a'] > 0) {
14 inStack[stack.Pop() - 'a'] = false;
15 }
16 stack.Push(c);
17 inStack[c - 'a'] = true;
18 }
19 char[] result = stack.ToArray();
20 Array.Reverse(result);
21 return new string(result);
22 }
23
24 public static void Main(string[] args) {
25 Solution solution = new Solution();
26 Console.WriteLine(solution.RemoveDuplicateLetters("cbacdcbc"));
27 }
28}The C# version utilizes a stack and array structures to ensure the resultant string is the smallest lexicographical order by checking and flipping our internal boolean array for stack inclusion leveraging conditions similar to other implementations.
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.
1using System.Collections.Generic;
public class Solution {
public string RemoveDuplicateLetters(string s) {
int[] freq = new int[26];
bool[] used = new bool[26];
foreach (char c in s) freq[c - 'a']++;
Stack<char> result = new Stack<char>();
foreach (char c in s) {
freq[c - 'a']--;
if (used[c - 'a']) continue;
while (result.Count > 0 && result.Peek() > c && freq[result.Peek() - 'a'] > 0) {
used[result.Pop() - 'a'] = false;
}
result.Push(c);
used[c - 'a'] = true;
}
char[] res = result.ToArray();
Array.Reverse(res);
return new string(res);
}
public static void Main(string[] args) {
Solution solution = new Solution();
Console.WriteLine(solution.RemoveDuplicateLetters("cbacdcbc"));
}
}The C# iteration also utilizes add-on string crafting, preserving maximal character verification efficiency not compromising minimal space considerations in building results.