Code Logo

Clear Digits

Published at23 Jul 2026
Easy 0 views
Like0

You are given a string consisting of lowercase English letters and digits. A digit character removes the closest non-digit character to its left (if one exists). After processing all digits, return the resulting string.

A stack handles this naturally: iterate through each character. If it's a digit and the stack is not empty, pop the top. Otherwise, push the character. At the end, the stack contains the remaining characters in order.

For example, "cb34" → c pushed, b pushed, 3 pops b, 4 pops c. Result is empty. "a1b2c3" → a pushed, 1 pops a, b pushed, 2 pops b, c pushed, 3 pops c. Empty.

This is similar to the Backspace String Compare problem, but instead of backspace #, any digit triggers the removal. The key difference is that digits always pop, and non-digits always push. There is no special case for consecutive digits — each digit pops one non-digit character.

This problem is commonly asked in entry-level technical interviews to assess understanding of fundamental stack behavior and array construction patterns. The solution is straightforward once you recognize that the stack operations map directly to the problem requirements.

Example Input & Output

Example 1
Input
"cb34"
Output
""
Explanation

Digits cancel all.

Example 2
Input
"abc"
Output
"abc"
Explanation

No digits.

Example 3
Input
"a1bc"
Output
"bc"
Explanation

1 pops a.

Algorithm Flow

Recommendation Algorithm Flow for Clear Digits
Recommendation Algorithm Flow for Clear Digits

Solution Approach

Iterate, push non-digits onto stack. If digit and stack not empty, pop.

function solution(s) {
  var stack = [];
  for (var i = 0; i < s.length; i++) {
    if (s[i] >= "0" && s[i] <= "9") { if (stack.length) stack.pop(); }
    else stack.push(s[i]);
  }
  return stack.join("");
}

Time O(n), Space O(n).

Best Answers

java
import java.util.*;
class Solution {
    public String solution(String s) {
        Stack<Character> stack = new Stack<>();
        for (char ch : s.toCharArray()) {
            if (ch >= '0' && ch <= '9') { if (!stack.isEmpty()) stack.pop(); }
            else stack.push(ch);
        }
        StringBuilder sb = new StringBuilder();
        for (char ch : stack) sb.append(ch);
        return sb.toString();
    }
}