#3174
Clear Digits
EasyStringStackSimulationStackString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a stack to efficiently keep track of non-digit characters. When a digit is encountered, we pop from the stack to remove the last non-digit character, achieving the desired result in a single pass.
⚙️
Algorithm
5 steps- 1Step 1: Initialize an empty stack.
- 2Step 2: Iterate through each character in the string.
- 3Step 3: If the character is a digit, pop the top of the stack (if not empty).
- 4Step 4: If the character is not a digit, push it onto the stack.
- 5Step 5: After processing all characters, the stack contains the result. Convert it back to a string.
solution.py10 lines
1s = 'cb34'
2stack = []
3for char in s:
4 if char.isdigit():
5 if stack:
6 stack.pop()
7 else:
8 stack.append(char)
9result = ''.join(stack)
10print(result)ℹ
Complexity note: This complexity is linear because we make a single pass through the string, and the stack can grow to the size of the input string in the worst case.
- 1Using a stack allows for efficient removal of characters without multiple scans.
- 2Understanding how to manipulate data structures like stacks is crucial for solving string problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.