15% off all plans & roadmaps Use code
See plansRemoving Stars From a String
- LeetCode 2390
- Medium
- Two Pointers
- String Comparison with Backspaces
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^5sconsists 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.
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.
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
- While
scontains a star, find the indexiof the first star. - Build a new string from
s[0 .. i - 2]followed bys[i + 1 ..]. This drops the letter ati - 1and the star ati. - Repeat from the top with the shorter string.
- 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
| Time | O(n^2) |
|---|---|
| Space | O(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 sApproach 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
- Create an empty stack of characters.
- For each character
cfrom left to right, pop the top ifcis a star. - Otherwise push
conto the stack. - 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
| Time | O(n) |
|---|---|
| Space | O(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 infographicSolution 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
- Copy
sinto a mutable character buffer. Python and Java strings cannot be changed in place. - Set
writeto 0. It marks the next free slot, which is the top of the stack. - Move
readfrom 0 to n - 1. Ifbuffer[read]is a star, decrementwrite. - Otherwise copy
buffer[read]tobuffer[write]and incrementwrite. - Return the first
writecharacters of the buffer.
Dry run
The table shows the state after each step. The valid prefix is buffer[0 .. write - 1].
| read | char | write before | action | write after | valid prefix |
|---|---|---|---|---|---|
| 0 | l | 0 | copy to slot 0 | 1 | l |
| 1 | e | 1 | copy to slot 1 | 2 | le |
| 2 | e | 2 | copy to slot 2 | 3 | lee |
| 3 | t | 3 | copy to slot 3 | 4 | leet |
| 4 | * | 4 | decrement | 3 | lee |
| 5 | * | 3 | decrement | 2 | le |
| 6 | c | 2 | copy to slot 2, overwriting the old e | 3 | lec |
| 7 | o | 3 | copy to slot 3, overwriting the old t | 4 | leco |
| 8 | d | 4 | copy to slot 4 | 5 | lecod |
| 9 | * | 5 | decrement | 4 | leco |
| 10 | e | 4 | copy to slot 4, overwriting the old d | 5 | lecoe |
The loop ends with write at 5, so the answer is lecoe.
Complexity
| Time | O(n) |
|---|---|
| Space | O(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 firstwritecharacters. The slots afterwritestill hold stale letters and stars. Return the prefix up towrite. - Writing
s[write] = s[read]in Python. Strings are immutable, so this raises a TypeError. Calllist(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++ ors[:i] + s[i + 1:]. The star removes the letter before it, so the slice must start ati - 1. - Incrementing
writebefore checking for a star. Every star then counts as a kept letter. Branch on the star first, and changewritein only one branch. - Trusting the guarantee on a malformed input such as
*ab. The write index drops below 0 and the code crashes. Clampwriteat 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*returnsa. The first star removesb, and the second star removesc.aa**bbreturnsbb. The two stars remove both leading letters, one at a time.zreturnsz. A single letter with no stars passes through unchanged.erase*****returns the empty string. Stars keep popping until the buffer is empty.arepeated 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-upsRemoving 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
Related problems
- Backspace String Compare · same technique: String Comparison with Backspaces
- Crawler Log Folder · same technique: String Comparison with Backspaces
- Trapping Rain Water · next harder, same pattern
- Sort Colors · same pattern: Two Pointers
- 3Sum · same pattern: Two Pointers
- Container With Most Water · same pattern: Two Pointers
- Longest Palindromic Substring · same pattern: Two Pointers
- Remove Nth Node From End of List · same pattern: Two Pointers
- Find the Duplicate Number · same pattern: Two Pointers
- Reverse Integer · same pattern: Two Pointers