Knowledge Guide
HomeDSAAdvanced Patterns

medium Removing Stars From a String

Problem Statement

You have a string s that contains lowercase letters and stars *.

In single operation:

Return the resultant string after performing all such operations.

Note:- Each star will have a corresponding letter to remove.

Examples

Example 1

Example 2

Example 3

Constraints:

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 removes the 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 b and *, resulting in "acd*ef*". Next, remove d and *, resulting in "acef*". Finally, remove f and *, resulting in "ace".

Example 2

  • Input: s = "a*bc*def**g"
  • Expected Output: "bdg"
  • Justification: First, remove a and *, resulting in "bc*def**g". Next, remove c and *, resulting in "bdef**g". Then, remove f and *, resulting in "bde*g". Finally, remove e and *, resulting in "bdg".

Example 3

  • Input: s = "xy*z*ww*"
  • Expected Output: "xw"
  • Justification: First, remove y and *, resulting in "xz*ww*". Next, remove z and *, resulting in "xww*". Finally, remove w and *, resulting in "xw".

Constraints:

  • 1 <= s.length <= 105
  • s consists 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 time complexity, where n is the length of the string. This is the most efficient way to handle the problem since it processes each character only once.

Step-by-step Algorithm

  1. Initialize the Stack:

    • Use StringBuilder stack to simulate stack operations.
  2. Iterate Through the String:

    • For each character c in the string s:
      • If c is not '*':
        • Push c to stack.
      • Else (if c is '*'):
        • Remove the top character from stack as we need to remove the nearest character from the left whenever the * character is encountered.
  3. Return the Result:

    • Convert stack to a string and return the resultant string.

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']
    • * -> pop b -> stack: ['a']
    • c -> stack: ['a', 'c']
    • d -> stack: ['a', 'c', 'd']
    • * -> pop d -> stack: ['a', 'c']
    • e -> stack: ['a', 'c', 'e']
    • f -> stack: ['a', 'c', 'e', 'f']
    • * -> pop f -> stack: ['a', 'c', 'e']
  • Step 3: Join stack to form the result: "ace".

Code

java
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.

🪜 Hint ladder (no spoilers)

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.
🎨 Explain the approach visually

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.
🔍 Review my solution

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.
🔁 Drill the pattern

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.

📝 My notes