Lexicographically Minimum String After Removing Stars Problem
#3170
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3170.
You are given a string s. It may contain any number of '*' characters. Your task is to remove all '*' characters.
While there is a '*', do the following operation:
- Delete the leftmost
'*'and the smallest non-'*'character to its left. If there are several smallest characters, you can delete any of them.
Return the lexicographically smallest resulting string after removing all '*' characters.
Example 1:
Input: s = "aaba*"
Output: "aab"
Explanation:
We should delete one of the 'a' characters with '*'. If we choose s[3], s becomes the lexicographically smallest.
Example 2:
Input: s = "abc"
Output: "abc"
Explanation:
There is no '*' in the string.
Constraints:
1 <= s.length <= 10^5sconsists only of lowercase English letters and'*'.- The input is generated such that it is possible to delete all
'*'characters.
Solution
Approach: Indices per Letter
Keep, for each letter, a stack of the indices where it appeared, plus a rem array that marks removed positions. A * marks itself removed and also removes the smallest letter that is still available, choosing its rightmost occurrence (so the remaining string stays as small as possible). Any other character pushes its index on its letter's stack. At the end, keep the characters that were not marked.
Complexity: time O(26 n), space O(n).
from string import ascii_lowercase
from collections import defaultdict
class Solution:
def clearStars(self, s: str) -> str:
g = defaultdict(list)
n = len(s)
rem = [False] * n
for i, c in enumerate(s):
if c == "*":
rem[i] = True
for a in ascii_lowercase:
if g[a]:
rem[g[a].pop()] = True
break
else:
g[c].append(i)
return "".join(c for i, c in enumerate(s) if not rem[i])