medium Problem 8 Removing Stars From a String
Problem Statement
Given a string s, where * represents a star. We can remove a star along with its closest non-star character to its left in a single operation.
The task is to perform as many such operations as possible until all stars have been removed and return the resultant string.
Examples
Example 1
- Input:
"abc*de*f" - Expected Output:
"abdf" - Description: We remove
calong with*to get"abde*f", then removeealong with*to get"abdf"
Example 2
- Input:
"a*b*c*d" - Expected Output:
"d" - Description: We remove
aalong with*to get"b*c*d", then removebwith*to get"c*d", then removecwith*to get"d".
Example 3
- Input:
"abcd" - Expected Output:
"abcd" - Description: As there is no
*, the string remains the same.
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
Given a string s, where * represents a star. We can remove a star along with its closest non-star character to its left in a single operation.
The task is to perform as many such operations as possible until all stars have been removed and return the resultant string.
Examples
Example 1
- Input:
"abc*de*f" - Expected Output:
"abdf" - Description: We remove
calong with*to get"abde*f", then removeealong with*to get"abdf"
Example 2
- Input:
"a*b*c*d" - Expected Output:
"d" - Description: We remove
aalong with*to get"b*c*d", then removebwith*to get"c*d", then removecwith*to get"d".
Example 3
- Input:
"abcd" - Expected Output:
"abcd" - Description: As there is no
*, the string remains the same.
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 can use a stack to efficiently handle the removal of characters caused by asterisks. As we iterate through the string, we push each non-asterisk character onto the stack. When we encounter an asterisk, we pop the top character from the stack, effectively removing the last non-asterisk character encountered. This process mimics the removal of characters as specified by the asterisks.
After processing the entire string, the remaining elements in the stack represent the characters that survived the removal process. Finally, we iterate through the stack to reconstruct the string in the correct order, as the stack will have the characters in reverse order of their original appearance.
Step-by-Step Algorithm
-
Initialization:
- Create an empty stack to store characters.
- The stack will help us manage the characters in the input string, especially when encountering a '*' character.
-
Iterate through each character in the input string:
- Loop through the input string character by character.
-
Process each character:
- If the character is '*':
- Check if the stack is not empty:
- If the stack has at least one character, pop the top character from the stack. This simulates removing the character preceding the '*'.
- Check if the stack is not empty:
- If the character is not '*':
- Push the character onto the stack. This means we keep it in the final result.
- If the character is '*':
-
Construct the final result string:
- After the iteration, convert the stack into a string by joining all elements in the revese order.
- Return the final valid string.
Algorithm Walkthrough
-
Initialization:
- Input string:
"abc*de*f" - Stack:
[](empty)
- Input string:
-
Process each character:
- Character 'a':
- It is not a '*', so push 'a' onto the stack.
- Stack:
['a']
- Character 'b':
- It is not a '*', so push 'b' onto the stack.
- Stack:
['a', 'b']
- Character 'c':
- It is not a '*', so push 'c' onto the stack.
- Stack:
['a', 'b', 'c']
- Character '*':
- It is a '*', and the stack is not empty, so pop the top character ('c') from the stack.
- Stack:
['a', 'b']
- Character 'd':
- It is not a '*', so push 'd' onto the stack.
- Stack:
['a', 'b', 'd']
- Character 'e':
- It is not a '*', so push 'e' onto the stack.
- Stack:
['a', 'b', 'd', 'e']
- Character '*':
- It is a '*', and the stack is not empty, so pop the top character ('e') from the stack.
- Stack:
['a', 'b', 'd']
- Character 'f':
- It is not a '*', so push 'f' onto the stack.
- Stack:
['a', 'b', 'd', 'f']
- Character 'a':
-
Construct and return the final result string:
- The final processed string is
"abdf".
- The final processed string is
-
Return the final result:
- The final processed string is
"abdf".
- The final processed string is
Final Output:
- For the input
"abc*de*f", the output after removing '*' and the preceding characters is"abdf".
Code
Here is how we can implement this algorithm:
import java.util.Stack;
public class Solution {
// Method to remove '*' characters from a string
public String removeStars(String s) {
Stack<Character> stack = new Stack<>(); // Create a stack to store characters
for (char c : s.toCharArray()) {
// Loop through each character in the input string
if (c == '*' && !stack.empty()) {
// If the character is '*' and the stack is not empty
stack.pop(); // Pop (remove) the top character from the stack
} else if (c != '*') {
// If the character is not '*'
stack.push(c); // Push (add) the character to the stack
}
}
StringBuilder result = new StringBuilder();
while (!stack.isEmpty()) {
result.append(stack.pop());
}
return result.reverse().toString();
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.removeStars("abc*de*f")); // Output: "abdf"
System.out.println(solution.removeStars("a*b*c*d")); // Output: "d"
System.out.println(solution.removeStars("abcd")); // Output: "abcd"
}
}
Complexity Analysis
Time Complexity
-
Processing the input string: The algorithm iterates through each character in the input string
s. For each character, it performs either a push or pop operation on the stack, both of which take constant time,. Therefore, iterating over the string takes , where Nis the length of the input string. -
Building the result string: Converting stack into the string takes
time.
Overall time complexity: N is the length of the input string.
Space Complexity
-
Stack space: The stack stores characters from the input string. In the worst case (when no
*characters are present), the stack will contain all characters, which requiresspace. -
Result string space: The
resultstring is used to store the final result which also takesspace, as it holds the result of the same size as the input string (in the worst case).
Overall space complexity:
🤖 Don't fully get this? Learn it with Claude
Stuck on Problem 8 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 **Problem 8 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 **Problem 8 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 **Problem 8 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 **Problem 8 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.