Removing Stars From a String (LeetCode 2390): Solution and Explanation

Medium
String
Stack
Simulation

Each star in s deletes itself and the closest remaining letter to its left. Return the string once every star is gone. For leet**cod*e the answer is lecoe.

Intuition

Deleting characters from the middle of a string again and again is slow, and it is easy to lose track of which letter is "closest" after earlier deletions.

Read left to right and keep only the letters that have survived so far, in order. When a star arrives, the closest surviving letter to its left is simply the last one you kept.

Keeping things in order and always removing the last one is exactly a stack. Push letters, pop on a star, and the stack holds the answer at the end.

Approach: Stack of surviving letters

  1. Create an empty stack (a list, StringBuilder or byte slice).
  2. For each character ch of s: if it is a star, pop the top of the stack.
  3. Otherwise push ch.
  4. Join the stack from bottom to top and return it.

Step-by-step example

s = "leet**cod*e"
  1. Push l, e, e, t. Stack: leet.
  2. The first star pops t. Stack: lee.
  3. The second star pops e. Stack: le.
  4. Push c, o, d. Stack: lecod.
  5. The third star pops d. Stack: leco.
  6. Push e. Stack: lecoe, which is the answer.

Code: Python, Java, C++

1class Solution:
2    def removeStars(self, s: str) -> str:
3        stack = []
4        for ch in s:
5            if ch == '*':
6                stack.pop()
7            else:
8                stack.append(ch)
9        return "".join(stack)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each character is pushed or causes one pop, and the final join is linear.

Space

O(n)

With no stars the stack holds every letter of the input.

Other approaches

Write pointer in place (time O(n), space O(1) extra)

Treat a character array as the stack. Keep a write index: a letter is written at the index and the index moves right, a star moves the index one step left. The answer is the prefix before the write index.

Delete from the string directly (time O(n^2), space O(n))

Find the first star, delete it and the letter before it, and repeat. Each deletion shifts the rest of the string, so this is quadratic.

Common mistakes

  • Building the result with repeated string concatenation or slicing in a language with immutable strings, which turns the pass quadratic.
  • Removing the character just before the star in the original string instead of the closest surviving letter. After ** the second star must reach past the letter the first one removed.
  • Guarding the pop with an emptiness check and silently ignoring it. The problem guarantees every star has a letter to remove, so the guard is not needed, but it does no harm.

Frequently asked questions

Why does the order in which stars are processed not matter?

Each star always ends up removing the same letter: the nearest one to its left that no earlier star claimed. Processing left to right with a stack finds exactly that pairing, so the result is unique.

How is this related to Backspace String Compare?

A star behaves like a backspace key. Backspace String Compare applies the same rule to two strings and compares the results, and it can also be solved with the stack idea or by scanning from the right.

Can it be done without extra space?

Yes. Use the input as a character array and a write pointer as the stack top, so only O(1) extra space is used besides the output.