Skip to content
Problem 2390 · LeetCode 2390(opens in a new tab)

Removing Stars From a String

MediumStacks

You get a string s made of lower-case letters and stars (*). Each star is an eraser: it deletes the nearest letter to its left that has not been deleted yet, and then the star itself disappears.

Apply every star and return the string that remains. The input is built so that every star has a letter to erase, and the final string is the same whatever order you process the stars in.

Example 1

Input:  s = "cat*s**e"
Output: "ce"
Why:    the stars erase t, then s, then a
2 more examples and the constraints

Example 2

Input:  s = "go**"
Output: ""
Why:    two stars erase both letters

Example 3

Input:  s = "abc"
Output: "abc"
Why:    no stars, nothing changes

Constraints

  • 1 ≤ s.length ≤ 100,000
  • s holds lower-case English letters and *
  • Every star has a letter to its left that it can erase

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Erase in placeO(n²)
  2. StackO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 charactersVerdict
Erase in placeO(n²)
Correct, too slow on long input
StackO(n)
Best; one pass, no shifting

n = length of s.

Edge cases to test

  • Everything erased. Two letters followed by two stars return the empty string, not an error.
  • No stars at all. "abc" comes back unchanged.
  • Stars in a row. In abc*d followed by two more stars, the answer is "a": each star takes the next letter still standing, not one already erased.
  • Star right after a star. A star never erases another star; it skips back to the nearest letter that is still there.

Common mistakes

  • Erasing the character just before the star in the original string, even if an earlier star already deleted it.
  • Building the answer with repeated string concatenation or deletion, which turns the pass into O(n²).
  • Forgetting to step the index back after deleting in place, so a character is skipped.

How to talk through it

  1. 1Clarify. Is there always a letter for each star? Can the result be empty?
  2. 2Give the direct simulation. Delete each star and its letter in place; say the shifting makes it O(n²).
  3. 3Spot the stack. A star undoes the most recent surviving letter: last in, first out.
  4. 4Code the one pass. Push letters, pop on stars, join at the end. In Java use a StringBuilder as the stack.
  5. 5Test out loud. Run an input that erases everything and one with stars in a row before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?