Removing Stars From a String

MediumStack · String🧩 StackLeetCode #2390 ↗Updated

Problem

A string s mixes lowercase letters and '*' characters. Each star acts like a backspace: it erases itself together with the closest not-yet-erased letter on its left. Apply this for every star and return what remains. The input guarantees every star has a letter available to erase, and the result is unique.
Inputs = "leet**cod*e"Output"lecoe"
Inputs = "erase*****"Output""
Inputs = "ab*c"Output"ac"

1 ≤ s.length ≤ 105  ·  s has lowercase letters and '*'  ·  the operation is always possible

Try it yourself

Java
class Solution {
    public String removeStars(String s) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
A star always removes the most recently kept letter — last in, first out. So the kept letters form a stack: letters push, stars pop.
PatternStack

Instinct Things resolve in reverse order of arrival (brackets, adjacent pairs, nested expressions) - push now, pop when its partner shows up.

Memory hack Last in, first out - like a pile of plates, you only ever touch the one on top; every closer pops its opener.

Open the Stack guide →

Approaches

Brute ForceSimulate Each Star with Deletions

Time O(n2)Space O(n)

Find the leftmost star; the character just before it is the nearest kept letter (anything earlier is a letter, since earlier stars are already gone). Delete both and repeat. Every deletion shifts the tail of the buffer, so many stars make it quadratic.

Java
public String removeStars(String s) {
    StringBuilder sb = new StringBuilder(s);
    int i = 0;
    while (i < sb.length()) {
        if (sb.charAt(i) == '*') {
            sb.delete(i - 1, i + 1); // the star and its left letter, O(n) shift
            i--;                      // continue right where the letter was
        } else {
            i++;
        }
    }
    return sb.toString();
}

Direct translation of the rules, but O(n²) for star-heavy inputs.

At a glance

LevelApproachTimeSpace
Brute ForceSimulate Each Star with DeletionsO(n2)O(n)
BetterExplicit StackO(n)O(n)
OptimalWrite Pointer (char[] as Stack)O(n)O(n)
Common pitfalls
  • Erasing the nearest letter to the right of the star instead of the left.
  • Building the result with s.substring/string concatenation in a loop — O(n²).
  • Reading the Deque top-first — produces the answer reversed.
Interview tips
  • Spot the backspace analogy right away — it screams “stack”.
  • Note the guarantee means no empty-stack check is required (mention it anyway).
  • Finish with the in-place write pointer to show constant-factor awareness.
Pattern
Stack / write-pointer simulation → backspace-style edits that undo the most recent kept item.
My notes saved in this browser