Removing Stars From a String

Medium

Topics
StringStack

Given a string s with letters and *. Each * removes the closest non-star character to its left (and itself). Return the resulting string.

Example 1

inleet**cod*e
outlecoe
removed
Each * deletes itself and the nearest character to its left that is still there — which is exactly a stack pop. Result: lecoe.
Cells are the characters of the string; the small numbers underneath are indices.
Input:  s = "leet**cod*e"
Output: "lecoe"

Example 2

inerase*****
out
removed
Input:  s = "erase*****"
Output: ""

Constraints

  • 1 <= s.length <= 10^5
  • The operation is always possible.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Each star deletes the closest surviving character to its left. "Closest surviving to the left" is the definition of the top of a stack, so the whole problem is one push-or-pop pass.

The guarantee that the operation is always possible means there is never a star with an empty stack, so no emptiness check is needed — though it costs nothing to add one and it is worth saying why it is safe to omit.

Approach

  1. Walk the string once.
  2. On a letter, push it.
  3. On a star, pop.
  4. Join the stack.

Dry Run

s = "leet**cod*e"

  c   stack
  l   l
  e   le
  e   lee
  t   leet
  *   lee
  *   le
  c   lec
  o   leco
  d   lecod
  *   leco
  e   lecoe

answer "lecoe"

  "erase*****"  ->  ""     every letter is removed

Complexity

  • Time — O(n): one push or pop per character, and the final join is linear.
  • Space — O(n) for the stack, which is also the output. In a language with mutable strings the same idea runs in place with a write index and O(1) extra space.

Common Pitfalls

  • Repeatedly searching the string for a star and splicing it out. Each splice is O(n), so the whole thing is O(n²) and times out at 10⁵ characters.
  • Scanning right to left. The rule points left, so a reverse pass has to buffer stars and gets confusing for no gain.
  • Using string concatenation to build the result inside the loop. In most languages that is O(n) per append and quietly quadratic; a list or builder keeps it linear.
  • Treating the star as a character to delete and keep track of separately. The star consumes itself, so nothing about it reaches the output.
  • Adding a pop-on-empty guard and then concluding the input might be malformed. The constraints promise it is not; the guard is defensive, not corrective.

Full Solution — all languages

class Solution:
    def removeStars(self, s):
        stack = []
        for c in s:
            if c == "*":
                stack.pop()
            else:
                stack.append(c)
        return "".join(stack)
SensAI
Beta
Tap the mic to stop voice mode