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 - Optimal Solution INPUT String s = "abc3def2" a 0 b 1 c 2 3 3 d 4 e 5 f 6 2 7 = Digit (to remove) = Non-digit character Use Stack Approach Process characters L to R Stack stores non-digits Pop on digit encounter ALGORITHM STEPS 1 Initialize Stack Empty stack to hold chars 2 Process Each Char Iterate through string 3 Non-digit: Push Add to stack 4 Digit: Pop Stack Remove closest left char Stack Trace: a --> [a] b --> [a,b] c --> [a,b,c] 3 --> [a,b] pop c d --> [a,b,d] e --> [a,b,d,e] f --> [a,b,d,e,f] 2 --> [a,b,d,e] pop f FINAL RESULT Final Stack Contents: a b d e Output: "abde" OK Removed characters: 'c' and 'f' '3' removed 'c' (left neighbor) '2' removed 'f' (left neighbor) Time: O(n) | Space: O(n) Key Insight: The stack naturally tracks the "closest non-digit to the left" - when we encounter a digit, the top of stack is exactly the character to remove. This gives us O(n) time complexity since each character is pushed and popped at most once. TutorialsPoint - Clear Digits | Optimal Stack-Based Solution
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