Lexicographically Minimum String After Removing Stars - Problem

You are given a string s that may contain any number of '*' characters. Your task is to remove all '*' characters through a specific process.

While there is a '*' in the string, perform the following operation:

  • Delete the leftmost '*' character
  • Delete 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.

Input & Output

Example 1 — Basic Case
$ Input: s = "leet*cod*e"
Output: "lecoe"
💡 Note: First '*' removes 'e' (smallest among 'l','e','e','t'), leaving "let*cod*e". Next '*' removes 'd' (smallest among 'l','e','t','c','o','d'), giving final result "lecoe".
Example 2 — Multiple Same Characters
$ Input: s = "erase*****"
Output: ""
💡 Note: Each '*' removes the smallest available character: first removes 'a', then 'e', then 'e', then 'r', finally 's', leaving empty string.
Example 3 — No Stars
$ Input: s = "hello"
Output: "hello"
💡 Note: No '*' characters to process, so the original string is returned unchanged.

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of lowercase English letters and '*' characters
  • It is guaranteed that all '*' operations can be applied

Visualization

Tap to expand
Lexicographically Minimum String After Removing StarsInput:"leet*cod*e"Process:Remove smallest chars when encountering '*'Step 1:"leet*" → remove 'e' (smallest) → "let"Step 2:"letcod*" → remove 'd' (smallest) → "letco"Step 3:"letcoe" → add final 'e' → "lecoe"Output:"lecoe"
Understanding the Visualization
1
Input String
Original string with stars and characters
2
Process Stars
Remove stars and smallest characters
3
Final Result
Lexicographically smallest remaining string
Key Takeaway
🎯 Key Insight: Use a stack to efficiently track characters and greedily remove the smallest character when encountering each '*'
Asked in
Google 23 Amazon 18 Meta 15 Microsoft 12
23.6K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen