<AI/>
enru
All posts

Removing stars from a string

LeetCode 2390: Remove every star together with the closest non-star character to its left using a stack.

Difficulty
Medium
Published
Topics
#string#stack
Open on LeetCode

Problem Description

You are given a string s containing stars *.

In one operation, you can:

  • Choose a star in s
  • Remove the closest non-star character to its left, as well as the star itself.

Return the string after all stars have been removed.

Note

  • The input is generated so that the operation is always possible.
  • The resulting string is always unique.

Constraints

  • The length of s is in the range from 1 to 105
  • s consists only of * and lowercase English letters
  • The string is guaranteed to be valid

Examples

Input: "leet**cod*e"

Answer: "lecoe"

Solution

Honestly, this problem doesn't really deserve its medium difficulty: it is solved very simply.

All we need is a stack. We iterate over the string and for each character do the following:

  • if the character is not *, push it onto the stack
  • if the character is *, pop the previous character from the stack

After going through the whole string, the stack contains only the characters we need. All that is left is to join the stack into a string and return it.

typescript
export const removeStars = (s: string): string => {
  let res: string[] = [];
 
  for (let char of s) {
    if (char === '*') {
      res.pop();
    } else {
      res.push(char);
    }
  }
 
  return res.join('');
};

Complexity Analysis

Time Complexity

O(n), since we iterate over the entire string.

Space Complexity

O(n), since we create a stack to store the intermediate result.