#2390

Removing Stars From a String

Medium
StringStackSimulationStackSimulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a stack allows us to efficiently manage the characters as we process the string. When we encounter a star, we simply pop the last character from the stack, which represents the closest non-star character to the left.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize an empty stack.
  2. 2Step 2: Iterate through each character in the string.
  3. 3Step 3: If the character is not a star, push it onto the stack.
  4. 4Step 4: If the character is a star, pop the top character from the stack (if the stack is not empty).
  5. 5Step 5: After processing all characters, join the characters in the stack to form the result string.
solution.py9 lines
1def removeStars(s):
2    stack = []
3    for char in s:
4        if char != '*':
5            stack.append(char)
6        else:
7            if stack:
8                stack.pop()
9    return ''.join(stack)

Complexity note: The time complexity is O(n) because we process each character in the string once. The space complexity is O(n) in the worst case when there are no stars, and all characters are pushed onto the stack.

  • 1Using a stack helps manage the removal of characters efficiently.
  • 2The problem can be visualized as a series of undo operations, which is what stacks are designed for.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.