Removing Stars From a String - Problem

You are given a string s, which contains stars *.

In one operation, you can:

  • Choose a star in s.
  • Remove the closest non-star character to its left, as well as remove the star itself.

Return the string after all stars have been removed.

Note:

  • The input will be generated such that the operation is always possible.
  • It can be shown that the resulting string will always be unique.

Input & Output

Example 1 — Basic Star Removal
$ Input: s = "leet**cod*e"
Output: lecoe
💡 Note: Process left to right: 'leet' → stack has [l,e,e,t]. First '*' removes 't' → [l,e,e]. Second '*' removes 'e' → [l,e]. Then 'cod' → [l,e,c,o,d]. Another '*' removes 'd' → [l,e,c,o]. Finally 'e' → [l,e,c,o,e] = "lecoe"
Example 2 — All Characters Removed
$ Input: s = "erase*****"
Output: ""
💡 Note: Start with 'erase' in stack. Five stars remove all five characters one by one, leaving empty string
Example 3 — No Stars
$ Input: s = "hello"
Output: hello
💡 Note: No stars present, so all characters remain: 'hello'

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of lowercase English letters and stars *
  • The operation is always possible (guaranteed by problem)

Visualization

Tap to expand
Removing Stars From a StringInput: leet**cod*eleet**cod*eProcess: Stars remove characters to their leftOutput: lecoelecoeStars act like backspace keys, removing the character immediately to their left
Understanding the Visualization
1
Input
String with characters and stars
2
Process
Stars remove characters to their left
3
Output
Final string after all stars processed
Key Takeaway
🎯 Key Insight: Use a stack to simulate backspace behavior - push characters, pop on stars
Asked in
Amazon 15 Microsoft 12 Google 8
24.0K Views
Medium Frequency
~15 min Avg. Time
856 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