Removing Stars From a String

Updated on 24 June, 2025
Removing Stars From a String header image

Problem Statement

In this challenge, you are tasked with manipulating a string that contains both lowercase English letters and asterisk characters (*). For each asterisk found in the string, you will execute a specific operation: you are to identify the closest non-asterisk character located to the left of that asterisk, and then remove both the identified character and the asterisk itself from the string. You need to process the string from left to right, performing this operation on each asterisk encountered. The final state of the string, after applying all possible operations, is the desired result. This process is guaranteed to be valid for all strings provided as input, and it is assured that the resulting string will be unique for any input string adhering to the rules.

Examples

Example 1

Input:

s = "vult**cod*e"

Output:

"vulcoe"

Explanation:

Performing the removals from left to right:

  • The closest character to the 1st star is 't' in "vult**cod*e". The string becomes "vul*cod*e".
  • The closest character to the 2nd star is 'l' in "vul*cod*e". The string becomes "vucod*e".
  • The closest character to the 3rd star is 'd' in "vucod*e". The string becomes "vulcoe".

There are no more asterisks, so we return "vulcoe".

Example 2

Input:

s = "erase*****"

Output:

""

Explanation:

The entire string is removed by repeated operations on each asterisk, so we return an empty string.

Constraints

  • 1 <= s.length <= 10^5
  • s consists of lowercase English letters and stars *.
  • The operation above can be performed on s.

Approach and Intuition

  1. Understanding the process: At each asterisk (*) encountered in the string, the operation requires removing the closest prior non-asterisk character. This compresses the string through repeated backspace-like behavior.

  2. Sequential processing: Loop through the string left to right:

    • If the character is not a *, save it (push onto a stack).
    • If it is a *, remove the most recent character (pop from the stack).
  3. Why Stack Works Well: Since the problem mimics a backspace action (remove the latest character before the *), a stack provides the right structure due to its Last-In, First-Out (LIFO) behavior.

  4. Final Assembly: After processing the entire string, the stack holds the characters that remain. Join them to get the result.

**Example Revisited (s = "vult**cod*e"):**

  • Characters processed: push 'v', 'u', 'l', 't'
  • At first *: pop 't'
  • At second *: pop 'l'
  • Continue: push 'c', 'o', 'd'
  • At third *: pop 'd'
  • Finally: push 'e'
  • Stack = ['v', 'u', 'l', 'c', 'o', 'e']"vulcoe"

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    string deleteStars(string str) {
        stack<char> chars;
        for (char c : str) {
            if (c == '*') {
                chars.pop();
            } else {
                chars.push(c);
            }
        }

        string output = "";
        while (!chars.empty()) {
            output += chars.top();
            chars.pop();
        }

        reverse(output.begin(), output.end());
        return output;
    }
};

The provided C++ solution addresses the problem of removing characters from a string when a '*' character is encountered. Here is how the implementation works:

  • A stack is utilized to store characters from the string as they are processed.
  • As you iterate over the string, each character is evaluated:
    • If the character is '', the top character of the stack is removed (this simulates the removal of the last non-star character due to the '').
    • If the character is not '*', it is added to the stack for possible future removal or to be part of the final processed string.
  • After iterating through all the characters, the stack holds all the characters that have not been "removed" by a '*'.
  • The final string is constructed by popping characters from the stack, thus reversing them to maintain the original order (as the stack would have the first character on the bottom).
  • Reverse the string to restore the original character order from the stack's reverse order.

In this way, the function efficiently processes the string by leveraging the LIFO (last-in, first-out) nature of a stack, allowing for the removal of characters associated with each ''. The use of stack ensures that each character is processed only once, and reversing the string at the end corrects the order of characters, yielding the desired result without retaining any of the '' characters.

java
class Solution {
    public String processStars(String s) {
        Stack<Character> chars = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '*') {
                if (!chars.isEmpty()) {
                    chars.pop();
                }
            } else {
                chars.push(s.charAt(i));
            }
        }

        StringBuilder result = new StringBuilder();
        while (!chars.isEmpty()) {
            result.append(chars.pop());
        }

        return result.reverse().toString();
    }
}

The Java program titled "Removing Stars From a String" offers an efficient solution to edit a string by removing specific characters influenced by asterisks. When an asterisk (*) appears in the string, it signifies the removal of the character immediately before it. The solution utilizes a Stack data structure to handle the characters of the string, allowing for dynamic addition and removal of characters according to the rules specified.

Below are the key steps the program follows to achieve the desired outcome:

  1. Create an instance of Stack to store characters as they are processed.
  2. Iterate over each character of the input string.
    • If the current character is an asterisk (*), check if the stack is not empty and pop the last character from the stack.
    • If it's not an asterisk, push the character onto the stack.
  3. Once the iteration is complete, initialize a StringBuilder to help reverse the characters collected in the stack (as they would be in LIFO order).
  4. Pop characters from the stack and append them to the StringBuilder until the stack is empty.
  5. Reverse the StringBuilder content to maintain the original sequence of the unremoved characters and convert it to a string for the final result.

This approach ensures that each character is effectively handled according to its context related to preceding asterisks, and the usage of Stack ensures an optimal solution both in terms of clarity and computational efficiency. The final string represents the input string stripped of characters that were marked for removal by asterisks.

python
class Solution:
    def starRemoval(self, s):
        stack = []
        for char in s:
            if char == '*':
                stack.pop()
            else:
                stack.append(char)

        return ''.join(stack)

In this solution summary, the task is to develop a Python function to remove stars from a string and all characters immediately preceding them.

  1. Define a class named Solution with a method starRemoval(self, s).
  2. Initialize an empty list called stack that will temporarily store characters from the input string s.
  3. Use a for loop to iterate through each character in the string s.
  4. Within the for loop, check if the current character is a star (*). If it is, remove the last character from the stack using pop(). If the character isn’t a star, append it to stack.
  5. After the loop finishes, return the resulting string by joining all the characters left in stack using join().

This method efficiently manages the modifications to the string by using a stack structure, avoiding direct manipulation of the string itself, which can be computationally expensive.

Comments

No comments yet.