Removing Stars From a String - Problem
You are given a string s containing letters and stars (*). Your task is to simulate a backspace operation where each star removes the closest non-star character to its left.
The Process:
- When you encounter a star
*, remove the closest non-star character to its left - Also remove the star itself
- Repeat until all stars are processed
Goal: Return the final string after all stars have been removed and processed.
Note: The input guarantees that every star will have at least one non-star character to its left, so the operation is always valid.
Example: "abc*de*f" becomes "adf" because the first * removes 'c', and the second * removes 'e'.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "leet**cod*e"
โบ
Output:
"lecoe"
๐ก Note:
Processing left to right: 'l','e','e','t' get added, first '*' removes 't', second '*' removes 'e', then 'c','o','d' get added, third '*' removes 'd', finally 'e' gets added. Result: "lecoe"
example_2.py โ Simple Case
$
Input:
s = "erase*****"
โบ
Output:
""
๐ก Note:
The string 'erase' has 5 characters, and there are 5 stars. Each star removes one character from left to right: 'e' removed, 'r' removed, 'a' removed, 's' removed, 'e' removed. Final result is empty string.
example_3.py โ No Stars
$
Input:
s = "abc"
โบ
Output:
"abc"
๐ก Note:
No stars in the string, so no characters are removed. The result is the original string "abc".
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Stack
Start with an empty stack to represent the text buffer
2
Process Characters
For each regular character, add it to the buffer (push to stack)
3
Handle Backspaces
For each star (*), remove the most recent character (pop from stack)
4
Build Result
The final stack contents represent the text after all backspaces
Key Takeaway
๐ฏ Key Insight: The stack data structure perfectly mimics a text editor's buffer, making this an elegant and efficient solution that processes each character exactly once.
Time & Space Complexity
Time Complexity
O(n)
Single pass through the string, each character is processed once
โ Linear Growth
Space Complexity
O(n)
Stack can contain at most n characters in worst case (no stars)
โก Linearithmic Space
Constraints
- 1 โค s.length โค 105
- s consists of lowercase English letters and stars *
- The given string is valid (every star has a non-star character to its left)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code