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.
1def removeDuplicateLetters(s: str) -> str:
2 from collections import Counter
3 freq = Counter(s)
4 stack = []
5 in_stack = set()
6
7 for char in s:
8 freq[char] -= 1
9 if char in in_stack:
10 continue
11 while stack and stack[-1] > char and freq[stack[-1]] > 0:
12 in_stack.remove(stack.pop())
13 stack.append(char)
14 in_stack.add(char)
15
16 return ''.join(stack)
17
18print(removeDuplicateLetters("cbacdcbc"))The Python implementation uses a stack to keep track of the correct order and a set to check if a character is already in the stack. The Counter from the collections module helps in efficiently counting character frequencies.
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
JavaScript employs constant arrays allowing for articulated handling mechanisms managing storage, addition, and subtractions on a per-character basis within entire execution cycle