Clear Digits - Problem

You are given a string s. Your task is to remove all digits by doing this operation repeatedly:

Delete the first digit and the closest non-digit character to its left.

Return the resulting string after removing all digits.

Note that the operation cannot be performed on a digit that does not have any non-digit character to its left.

Input & Output

Example 1 — Basic Case
$ Input: s = "abc3def2"
Output: "abde"
💡 Note: First digit '3': remove '3' and closest left non-digit 'c' → "ab_def2". Next digit '2': remove '2' and closest left non-digit 'f' → "abde"
Example 2 — Digit Without Left Non-Digit
$ Input: s = "2ab3"
Output: "a"
💡 Note: First digit '2': no non-digit to its left, remove only '2' → "ab3". Next digit '3': remove '3' and closest left non-digit 'b' → "a"
Example 3 — All Digits
$ Input: s = "123"
Output: "123"
💡 Note: No non-digit characters exist, so no digits can be removed. Return original string

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists of lowercase English letters and digits

Visualization

Tap to expand
Clear Digits Problem OverviewInput:abc3def2"abc3def2"Remove c+3Remove f+2Process:1. Find digit '3' → Remove '3' and closest left non-digit 'c'2. Find digit '2' → Remove '2' and closest left non-digit 'f'Output:abde"abde"
Understanding the Visualization
1
Input String
String with letters and digits mixed together
2
Remove Pairs
Each digit removes itself and closest left non-digit
3
Final Result
Remaining characters after all valid removals
Key Takeaway
🎯 Key Insight: Use a stack to naturally track the closest left non-digit for efficient removal
Asked in
Microsoft 15 Amazon 12
29.8K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen