CMD 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:

🎯 STRICT STANDOUT — Removing Stars From a String (problem)

0. Why this page exists

Family: Stack / string collapse (backspace simulation)

Classic 'typewriter with backspace' shape: * deletes nearest left letter. Stack (or string builder) is the linear pattern; naive string concat would be quadratic.

1. Pattern + when-NOT (K12)

Pattern / template: For each char: if letter push; if '*' pop (problem guarantees a letter exists). Join stack. Equivalent: two-pointer write index into char array.

When-NOT: When-NOT regex/global replace without stack order; when-NOT matching parentheses with types (need typed stack); when-NOT if * deletes rightward. When-NOT DP on strings — no optimal substructure, pure simulation.

2. Complexity derivation (K11)

One pass O(n) time; stack ≤n → O(n) space.
Naive: each * rebuilds string → O(n²) worst ("a"*n + "*"*n patterns).

3. Edge hand-run (K13)

ab*cd*ef* → ace.
a*bc*def**g → bdg.
All stars cancel all letters → "". Consecutive ** after letters pops twice.

4. Interviewer follow-ups & drills

Q1. Why stack not queue?
Model answer: Deletion is always nearest left = LIFO of remaining letters.

Q2. In-place two pointer?
Model answer: Write index i; on letter s[i++]=c; on * i-- if i>0.

Q3. Unicode / multi-byte?
Model answer: Problem is ASCII letters; general backspace needs grapheme care.

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

🎯 STRICT STANDOUT — Solution Removing Stars From a String

0. Why this page exists

Family: Stack string collapse

Locks O(n) vs O(n²) rebuild and hand-runs multi-star collapses so learners feel amortized pops.

1. Pattern + when-NOT (K12)

Pattern / template: stack=[]; for c in s: if c!='*': stack.append(c) else: stack.pop(). return ''.join(stack).

When-NOT: When-NOT if stars can appear without left letter (guard empty). When-NOT balanced bracket validation (types + order). Prefer two-pointer if interview forbids aux list.

2. Complexity derivation (K11)

Time O(n): each char once; join O(n).
Space O(n) worst (no stars).
Not O(n log n) — no sorting of characters.

3. Edge hand-run (K13)

"ab*cd*ef*" → stack path: a,b,pop→a,c,d,pop→ac,e,f,pop→ace.
"a*" → "". "abc" no stars → "abc".
Guarantee: operation always valid so pop never on empty.

4. Interviewer follow-ups & drills

Q1. Amortized cost of pops?
Model answer: Each letter pushed once and popped at most once → total O(n).

Q2. Relate to Validate Stack Sequences?
Model answer: Both are LIFO simulations; here ops are inline in one string.

Q3. StringBuilder vs stack of chars?
Model answer: Same asymptotics; careful with language string immutability.

🧩 Pattern · Arrays

Recognize it: Scan once tracking what you need (running max/sum), or precompute a prefix-sum / hash → turn O(n²) into O(n).

▶ Visualize this problem (step it, predict each fork)
⛶ Open this problem debugger in explore mode
🤖 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