Lexicographically Minimum String After Removing Stars - Problem
You're given a string s containing lowercase letters and asterisks (*). Your mission is to remove all asterisks by following a specific elimination rule that will give you the lexicographically smallest possible result.
The Elimination Rule: For each asterisk (*) you encounter:
- Find the leftmost asterisk
- Look to its left and find the smallest character (lexicographically)
- Remove both the asterisk and that smallest character
- If there are multiple smallest characters, you can remove any one of them
Goal: Return the lexicographically smallest string after removing all asterisks.
Example: In "abc*de*", the first * removes 'a' (smallest to its left), and the second * removes 'b', leaving "cde".
Input & Output
example_1.py โ Basic Case
$
Input:
s = "leet*cod*e"
โบ
Output:
"letcode"
๐ก Note:
First '*' removes smallest char to its left ('e' from 'leet'), leaving 'let*cod*e'. Second '*' removes 't', leaving 'lecod*e'. Last '*' removes 'c', giving final result 'letcode'.
example_2.py โ Multiple Same Characters
$
Input:
s = "erase*****"
โบ
Output:
""
๐ก Note:
Each '*' removes one character: 'erase****' โ 'rase***' โ 'ase**' โ 'se*' โ 'e' โ ''. All characters are eliminated.
example_3.py โ No Stars
$
Input:
s = "abc"
โบ
Output:
"abc"
๐ก Note:
No asterisks present, so the string remains unchanged.
Constraints
- 1 โค s.length โค 105
- s consists of lowercase English letters and '*' characters
- It is guaranteed that the string can be processed (no asterisk without preceding characters)
Visualization
Tap to expand
Understanding the Visualization
1
Add to Stack
Place each character on the stack as you encounter it
2
Track in Heap
Also add each character to a min-heap for quick smallest-element access
3
Process Asterisk
When you see *, remove the smallest character from heap and mark its stack position
4
Build Result
Collect all non-removed characters from the stack in their original order
Key Takeaway
๐ฏ Key Insight: The combination of stack (for order preservation) and min-heap (for efficient minimum finding) gives us the optimal balance between correctness and performance.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code