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 Stars INPUT s = "leet*cod*e" l e e t * c o d * e Indices: 0-9 Character Stacks (a-z) 'c' idx:5 'e' 1,2,9 'l' idx:0 ... o,t,d Track positions of each character in stacks Input String: "leet*cod*e" ALGORITHM STEPS 1 Build Char Stacks Store indices of each char 2 Process First * Find smallest char before * * at idx 4 Remove 'e' at idx 2 Result: "let*cod*e" 3 Process Second * Repeat for next star * at idx 8 Remove 't' at idx 3 Result: "lecod*e" 4 Build Final String Remove all * and deleted chars FINAL RESULT Deletion Process: Original: l e e t * c o d * e After 1st *: l e t c o d * e (removed 'e' at pos 2) After 2nd *: l e c o e (removed 'd' - smallest) Final String: l e c o e Output: "lecoe" OK - Lexicographically smallest! Greedy picks smallest char to delete at each step Key Insight: Use 26 stacks (one per letter) to track character positions. When encountering a '*', greedily remove the smallest character (earliest in alphabet) that appears BEFORE the star. This greedy approach ensures the lexicographically smallest result. Time: O(n), Space: O(n). TutorialsPoint - Lexicographically Minimum String After Removing Stars | Greedy with Smart Stack Management
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