#3170

Lexicographically Minimum String After Removing Stars

Medium
Hash TableStringStackGreedyHeap (Priority Queue)StackGreedy Algorithms
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)

The optimal approach uses a stack to efficiently manage the characters. We push non-'*' characters onto the stack, and when we encounter a '*', we pop the top character from the stack, effectively removing the smallest non-'*' character.

⚙️

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 '*', pop the top character from the stack (if not empty).
  4. 4Step 4: If the character is not '*', push it onto the stack.
  5. 5Step 5: After processing all characters, join the stack to form the result string.
solution.py9 lines
1def removeStars(s):
2    stack = []
3    for char in s:
4        if char == '*':
5            if stack:
6                stack.pop()
7        else:
8            stack.append(char)
9    return ''.join(stack)

Complexity note: The time complexity is O(n) since we traverse the string once and each character is pushed or popped from the stack at most once. The space complexity is O(n) due to the stack storing characters.

  • 1Using a stack allows us to efficiently manage the removal of characters, ensuring we always remove the most recent character when a '*' is encountered.
  • 2The order of operations is crucial; processing characters in a single pass ensures we maintain the correct lexicographical order.

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