medium Removing Stars From a String
Problem Statement
You have a string s that contains lowercase letters and stars *.
In single operation:
- Choose any star in the string
s. - Each star
removesthe closest letter to its left along with itself.
Return the resultant string after performing all such operations.
Note:- Each star will have a corresponding letter to remove.
Examples
Example 1
- Input:
s = "ab*cd*ef*" - Expected Output:
"ace" - Justification: First, remove
band*, resulting in"acd*ef*". Next, removedand*, resulting in"acef*". Finally, removefand*, resulting in"ace".
Example 2
- Input:
s = "a*bc*def**g" - Expected Output:
"bdg" - Justification: First, remove
aand*, resulting in"bc*def**g". Next, removecand*, resulting in"bdef**g". Then, removefand*, resulting in"bde*g". Finally, removeeand*, resulting in"bdg".
Example 3
- Input:
s = "xy*z*ww*" - Expected Output:
"xw" - Justification: First, remove
yand*, resulting in"xz*ww*". Next, removezand*, resulting in"xww*". Finally, removewand*, resulting in"xw".
Constraints:
- 1 <= s.length <= 105
sconsists of lowercase English letters and stars*.- The operation above can be performed on
s.
Try it yourself
Try solving this question here:
✅ Solution Removing Stars From a String
Problem Statement
You have a string s that contains lowercase letters and stars *.
In single operation:
- Choose any star in the string
s. - Each star
removesthe closest letter to its left along with itself.
Return the resultant string after performing all such operations.
Note:- Each star will have a corresponding letter to remove.
Examples
Example 1
- Input:
s = "ab*cd*ef*" - Expected Output:
"ace" - Justification: First, remove
band*, resulting in"acd*ef*". Next, removedand*, resulting in"acef*". Finally, removefand*, resulting in"ace".
Example 2
- Input:
s = "a*bc*def**g" - Expected Output:
"bdg" - Justification: First, remove
aand*, resulting in"bc*def**g". Next, removecand*, resulting in"bdef**g". Then, removefand*, resulting in"bde*g". Finally, removeeand*, resulting in"bdg".
Example 3
- Input:
s = "xy*z*ww*" - Expected Output:
"xw" - Justification: First, remove
yand*, resulting in"xz*ww*". Next, removezand*, resulting in"xww*". Finally, removewand*, resulting in"xw".
Constraints:
- 1 <= s.length <= 105
sconsists of lowercase English letters and stars*.- The operation above can be performed on
s.
Solution
To solve this problem, we'll use a stack to simulate the removal process. The stack will help us keep track of characters that haven't been removed yet. When we encounter a star *, we remove the top character from the stack, as it represents the closest letter to the left. This approach is effective because it directly mimics the described removal process, ensuring we handle each star in the correct order.
The stack-based simulation approach ensures that each star removes the correct character in
Step-by-step Algorithm
-
Initialize the Stack:
- Use
StringBuilder stackto simulate stack operations.
- Use
-
Iterate Through the String:
- For each character
cin the strings:- If
cis not '*':- Push
ctostack.
- Push
- Else (if
cis '*'):- Remove the top character from
stackas we need to remove the nearest character from the left whenever the*character is encountered.
- Remove the top character from
- If
- For each character
-
Return the Result:
- Convert
stackto a string and return the resultant string.
- Convert
Algorithm Walkthrough
Let's consider the input: s = "abcdef*"
- Step 1: Initialize an empty stack:
[]. - Step 2: Process characters:
a-> stack:['a']b-> stack:['a', 'b']*-> popb-> stack:['a']c-> stack:['a', 'c']d-> stack:['a', 'c', 'd']*-> popd-> stack:['a', 'c']e-> stack:['a', 'c', 'e']f-> stack:['a', 'c', 'e', 'f']*-> popf-> stack:['a', 'c', 'e']
- Step 3: Join stack to form the result:
"ace".
Code
public class Solution {
public String removeStars(String s) {
// Use StringBuilder as a stack
StringBuilder stack = new StringBuilder();
// Iterate through each character in the string
for (char c : s.toCharArray()) {
if (c != '*') {
// If character is not '*', push it onto the stack
stack.append(c);
} else {
// If character is '*', pop the top character from the stack
stack.deleteCharAt(stack.length() - 1);
}
}
// Convert stack to string
return stack.toString();
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.removeStars("ab*cd*ef*")); // Output: "ace"
System.out.println(solution.removeStars("a*bc*def**g")); // Output: "bdg"
System.out.println(solution.removeStars("xy*z*ww*")); // Output: "xw"
}
}
Complexity Analysis
- Time Complexity:
- We process each character of the string exactly once. - Space Complexity:
- In the worst case, the stack may store all characters of the string.
🤖 Don't fully get this? Learn it with Claude
Stuck on Removing Stars From a String? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Removing Stars From a String** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Removing Stars From a String** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Removing Stars From a String**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Removing Stars From a String**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.