15% off all plans & roadmaps Use code

See plans

Removing Stars From a String

Updated

TL;DR: Each star deletes the nearest surviving letter to its left, along with itself. Track the survivors with a stack or a write index. Every star undoes the last kept letter, which gives an O(n) single pass.

Problem

You are given a string s that contains stars *. One operation does two things. First, choose a star. Second, remove the closest non-star character to its left, along with the star itself.

Return the string that remains after every star is removed.

The input is generated so that the operation is always possible. The resulting string is always unique.

Example 1

Input: s = "leet**cod*e"
Output: "lecoe"
Explanation:
- Remove t with the 1st star: lee*cod*e
- Remove e with the 2nd star: lecod*e
- Remove d with the 3rd star: lecoe

Example 2

Input: s = "erase*****"
Output: ""

Constraints

  • 1 <= s.length <= 10^5
  • s consists of lowercase English letters and stars *.
  • The operation can be performed on s.

Constraints that matter

  • n up to 10^5 rules out rebuilding the string once per star, because that costs O(n^2) in the worst case.
  • Every star needs a letter before it, so the number of stars is at most n / 2. Stars never outnumber letters.
  • Letters that survive keep their original order. The nearest survivor to a star is always the most recent one, which is why a stack or a write index works.
  • Lowercase letters and stars only. You can compare characters directly with '*' and never handle Unicode.

View on LeetCode

Hints

Hint 1

A star works like a backspace key.

Hint 2

A beginner reads the rule and applies it literally.

Solution

Intuition

A star works like a backspace key. Each star undoes the most recent letter still on the page. Undoing the newest item first is last in, first out behavior, so a stack fits.

Picture a stack of plates where each kept letter is a plate. A star takes the top plate off, and the write index is the height of the pile.

A star never searches far. It always removes the nearest surviving letter, and you already know where that letter is. The answer depends only on the letters you kept so far, so you can read the string once from left to right.

The same idea appears as two pointers with a write index. The write index marks the top of the kept letters. A letter copies to the write slot and moves the index forward, while a star moves it back by one. The write index reuses the input array instead of allocating a second one.

Watch the pattern animation

Worked example

Input: s = "leet**cod*e"
Output: "lecoe"
Explanation: The first star removes t, the second removes e, and the third removes d. The letters that survive, in order, are l, e, c, o, e.

Approach 1: Brute force: rescan and rebuild

A beginner reads the rule and applies it literally. Find a star, delete it together with the letter before it, and repeat until no star is left. Every deletion builds a new string, so the search starts again from the front each time.

Steps

  1. While s contains a star, find the index i of the first star.
  2. Build a new string from s[0 .. i - 2] followed by s[i + 1 ..]. This drops the letter at i - 1 and the star at i.
  3. Repeat from the top with the shorter string.
  4. When no star is left, return s.

Dry run

The first star in leet**cod*e is at index 4. Removing indices 3 and 4 gives lee*cod*e, and the next star at index 3 removes indices 2 and 3 to give lecod*e. The last star is at index 5, so removing indices 4 and 5 gives lecoe. No star remains, so the answer is lecoe.

Complexity

TimeO(n^2)
SpaceO(n)

Let n be the length of s, and let k be the number of stars, where k is at most n / 2. Each round scans for the first star and rebuilds the string, which costs at most n steps. The k rounds therefore cost at most k * n, which is O(n^2) when k is near n / 2. Each rebuilt string holds up to n characters, so the extra space is O(n).

PythonTested in our runner

class Solution:
    def removeStars(self, s: str) -> str:
        while '*' in s:
            i = s.index('*')  # first star, always at index 1 or later
            s = s[:i - 1] + s[i + 1:]  # drop the letter before it and the star
        return s

Approach 2: Stack of surviving letters

What's slow: the brute force scans the string from the front and rebuilds it after every star, so the same letters are copied again and again. The insight that fixes it: the letters that survive stay in order, and each star removes the newest survivor. Last in, first out means a stack holds the survivors, and a star pops the top.

Steps

  1. Create an empty stack of characters.
  2. For each character c from left to right, pop the top if c is a star.
  3. Otherwise push c onto the stack.
  4. Read the stack from bottom to top and return it as a string.

Dry run

Push l, e, e and t to get [l, e, e, t]. The first star pops t, leaving [l, e, e], and the second star pops e, leaving [l, e]. Push c, o and d, then the third star pops d, leaving [l, e, c, o]. Push e to get [l, e, c, o, e], which reads lecoe.

Complexity

TimeO(n)
SpaceO(n)

Let n be the length of s. The loop visits each character once, so there are n iterations. Each character is pushed at most once and popped at most once, so the total stack work is at most 2n, which is O(n). The stack can hold up to n letters when the string has no stars, so the space is O(n).

PythonTested in our runner

class Solution:
    def removeStars(self, s: str) -> str:
        stack = []
        for c in s:
            if c == '*':
                stack.pop()  # remove the nearest surviving letter
            else:
                stack.append(c)
        return ''.join(stack)

The String Comparison with Backspaces infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

String Comparison with Backspaces

Part of Two Pointers

Approach 3: Two pointers with a write indexOptimalString Comparison with Backspaces

What's slow: the stack is a separate structure, and its size grows with every letter. The insight that fixes it: the top of the stack is always the slot just before the write index. Copying the kept letters to the front of the same array gives the same result with one buffer and two integers.

Why it is correct. The invariant is that after each prefix, the first write characters hold exactly the letters that survive that prefix. A star always removes the nearest surviving letter, so no other choice can change which letters survive. Later characters only push onto or pop from the top, so earlier results never need revisiting.

Steps

  1. Copy s into a mutable character buffer. Python and Java strings cannot be changed in place.
  2. Set write to 0. It marks the next free slot, which is the top of the stack.
  3. Move read from 0 to n - 1. If buffer[read] is a star, decrement write.
  4. Otherwise copy buffer[read] to buffer[write] and increment write.
  5. Return the first write characters of the buffer.

Dry run

The table shows the state after each step. The valid prefix is buffer[0 .. write - 1].

readcharwrite beforeactionwrite aftervalid prefix
0l0copy to slot 01l
1e1copy to slot 12le
2e2copy to slot 23lee
3t3copy to slot 34leet
4*4decrement3lee
5*3decrement2le
6c2copy to slot 2, overwriting the old e3lec
7o3copy to slot 3, overwriting the old t4leco
8d4copy to slot 45lecod
9*5decrement4leco
10e4copy to slot 4, overwriting the old d5lecoe

The loop ends with write at 5, so the answer is lecoe.

Complexity

TimeO(n)
SpaceO(n)

Let n be the length of s. The read pointer moves n times, and each step does constant work. The write pointer never passes the read pointer, so every copy lands on a slot that has already been read. The buffer takes O(n) space, and the only extra variables are the two integers.

PythonTested in our runner

class Solution:
    def removeStars(self, s: str) -> str:
        chars = list(s)  # strings are immutable, so use a list
        write = 0  # next free slot, acts as the stack top
        for read in range(len(chars)):
            if chars[read] == '*':
                write -= 1
            else:
                chars[write] = chars[read]
                write += 1
        return ''.join(chars[:write])

Common mistakes

  • Returning s[:read] or the whole buffer instead of the first write characters. The slots after write still hold stale letters and stars. Return the prefix up to write.
  • Writing s[write] = s[read] in Python. Strings are immutable, so this raises a TypeError. Call list(s) first and write into the list.
  • Comparing a char to a String in Java with c == "*". This does not compile. Compare with the char literal '*'.
  • Removing the star and the letter after it, as in s.erase(i, 2) in C++ or s[:i] + s[i + 1:]. The star removes the letter before it, so the slice must start at i - 1.
  • Incrementing write before checking for a star. Every star then counts as a kept letter. Branch on the star first, and change write in only one branch.
  • Trusting the guarantee on a malformed input such as *ab. The write index drops below 0 and the code crashes. Clamp write at 0 if the input is not validated.

Edge cases

  • a* returns the empty string. This is the smallest valid input with a star.
  • ab*c* returns a. The first star removes b, and the second star removes c.
  • aa**bb returns bb. The two stars remove both leading letters, one at a time.
  • z returns z. A single letter with no stars passes through unchanged.
  • erase***** returns the empty string. Stars keep popping until the buffer is empty.
  • a repeated 50000 times, followed by 50000 stars, returns the empty string. This input shows why the brute force costs O(n^2) and the optimal approaches stay linear.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Removing Stars From a String, with how to answer them.

Unlock the follow-ups

Removing Stars From a String FAQ

What is the time complexity of Removing Stars From a String?

The stack and two-pointer solutions run in O(n) time, where n is the length of s. The brute force that rebuilds the string after each star runs in O(n^2) time in the worst case. The optimal solutions do one constant-time step per character.

Why use two pointers for Removing Stars From a String?

A star removes the nearest surviving letter, so the kept letters always form a prefix that changes at one end. A write index tracks that end, and a read index walks the input once. This avoids the repeated rebuilding that makes the brute force slow.

Can Removing Stars From a String be solved in O(1) extra space?

Yes, if you may overwrite the input array. The write index reuses the buffer, so only two integers are extra. In Python or Java you still need a buffer of size n, because their strings are immutable, so the honest bound there is O(n).

Why does Python need list() for the two-pointer version?

Python strings cannot be changed by index assignment, so s[write] = s[read] raises a TypeError. Converting the string to a list gives a mutable buffer. Join the first write items at the end to build the answer.

Is a stack the same as two pointers here?

The two approaches make the same decisions. The stack stores survivors in a separate container, while the write index stores them in the front of the input array. The write index saves memory, and the stack is easier to explain first.

Asked at

See which companies ask this — Pro

Practise it