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.
- Erase in placeO(n²)
- StackO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 characters | Verdict |
|---|---|---|---|
| Erase in place | O(n²) | Correct, too slow on long input | |
| Stack | O(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*dfollowed 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
- 1Clarify. Is there always a letter for each star? Can the result be empty?
- 2Give the direct simulation. Delete each star and its letter in place; say the shifting makes it O(n²).
- 3Spot the stack. A star undoes the most recent surviving letter: last in, first out.
- 4Code the one pass. Push letters, pop on stars, join at the end. In Java use a StringBuilder as the stack.
- 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?