Clear Digits - Problem
You're given a string containing both letters and digits mixed together. Your task is to eliminate all digits by repeatedly applying a specific removal rule:
- Find the first digit in the string
- Remove both the digit AND the closest non-digit character to its left
- Repeat until no more digits can be removed
Important: If a digit has no non-digit character to its left, it cannot be removed and will remain in the final string.
Example: In "abc3def2", we first remove digit '3' and its closest left non-digit 'c', giving us "ab_def2". Then we remove '2' and 'f', resulting in "ab_de".
Input & Output
example_1.py โ Basic Case
$
Input:
s = "abc3def2"
โบ
Output:
"abde"
๐ก Note:
First, we remove '3' and its closest left non-digit 'c', getting 'ab_def2'. Then we remove '2' and 'f', resulting in 'abde'.
example_2.py โ Leading Digits
$
Input:
s = "123abc"
โบ
Output:
"123abc"
๐ก Note:
The digits '1', '2', '3' have no non-digit characters to their left, so they cannot be removed. The string remains unchanged.
example_3.py โ All Removable
$
Input:
s = "a1b2c3"
โบ
Output:
""
๐ก Note:
We can remove all digits: '1' removes 'a', '2' removes 'b', '3' removes 'c', leaving an empty string.
Visualization
Tap to expand
Understanding the Visualization
1
Type Characters
As we type non-digit characters, they appear on screen (get added to stack)
2
Hit 'Digit Backspace'
When we press a digit key, it acts like backspace - removes the last character and itself
3
Smart Deletion
The stack automatically tracks which character to delete (top of stack = most recent)
4
Final Text
What remains on screen is our final result after all digit-backspaces
Key Takeaway
๐ฏ Key Insight: The stack approach is optimal because it naturally maintains the order of characters and provides O(1) access to the "closest left non-digit" character, eliminating the need for repeated string operations.
Time & Space Complexity
Time Complexity
O(n)
We process each character exactly once, and each stack operation is O(1)
โ Linear Growth
Space Complexity
O(n)
In worst case (no digits), we store all characters in the stack
โก Linearithmic Space
Constraints
- 1 โค s.length โค 100
- s consists of lowercase English letters and digits
- The given operation can be performed on the string at most s.length times
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code