Lexicographically Smallest String After Deleting Duplicate Characters Problem
Description
LeetCode Problem 3816.
You are given a string s that consists of lowercase English letters.
You can perform the following operation any number of times (possibly zero times):
- Choose any letter that appears at least twice in the current string
sand delete any one occurrence.
Return the lexicographically smallest resulting string that can be formed this way.
Example 1:
Input: s = "aaccb"
Output: "aacb"
Explanation:
We can form the strings "acb", "aacb", "accb", and "aaccb". "aacb" is the lexicographically smallest one.
For example, we can obtain "aacb" by choosing 'c' and deleting its first occurrence.
Example 2:
Input: s = "z"
Output: "z"
Explanation:
We cannot perform any operations. The only string we can form is "z".
Constraints:
1 <= s.length <= 10^5scontains lowercase English letters only.
Solution
Approach: Monotonic Stack
Build the answer in a stack and keep cnt, the number of copies of each letter that are still allowed to be deleted (initially its count in s).
Scan the string. Before pushing a character c, pop the top of the stack while it is larger than c and its letter still has a spare copy (cnt > 1); each pop uses up one copy. Then push c.
After the scan the stack may still end with letters that have spare copies. Deleting a trailing letter only makes the string shorter and therefore smaller, so keep popping the top while its letter has a spare copy.
Complexity: O(n) time and O(n) space, where n is the length of s.
from collections import Counter
class Solution:
def lexSmallestAfterDeletion(self, s: str) -> str:
cnt = Counter(s)
stk = []
for c in s:
while stk and stk[-1] > c and cnt[stk[-1]] > 1:
cnt[stk.pop()] -= 1
stk.append(c)
while stk and cnt[stk[-1]] > 1:
cnt[stk.pop()] -= 1
return "".join(stk)