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 String INPUT s = "leet**cod*e" l e e t * * c o d * e Index: 0 1 2 3 4 5 6 7 8 9 10 Stack-based Approach Stack (LIFO) push char pop on * bottom ALGORITHM STEPS 1 Initialize Stack Create empty stack 2 Iterate String Process each character 3 Handle Characters Non-star: push to stack Star: pop from stack 4 Build Result Join stack contents Processing Steps: 'l' --> stack: [l] 'e' --> stack: [l,e] 'e' --> stack: [l,e,e] 't' --> stack: [l,e,e,t] '*' --> pop 't': [l,e,e] '*' --> pop 'e': [l,e] FINAL RESULT After processing all chars: Final Stack: l e c o e Output: "lecoe" [OK] All stars removed! Complexity: Time: O(n) Space: O(n) Key Insight: Use a stack to track characters. When encountering a star (*), pop the last character from the stack (removing the closest non-star to its left). This simulates the deletion operation in O(1) time per character, giving us an optimal O(n) solution overall. TutorialsPoint - Removing Stars From a String | Optimal Stack Solution
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