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
Digits cancel all.
No digits.
1 pops a.
Algorithm Flow
Solution Approach
Remove all digits from a string by erasing the closest non-digit character to the left of each digit. Use a stack: push non-digit characters. When a digit is encountered, pop the stack (removing the closest non-digit to the left). After processing all characters, the stack contains the result.
Each digit acts as a backspace that erases the preceding character. The stack naturally implements this last-in-first-out deletion pattern.
Time complexity is O(n), space complexity is O(n).
Best Answers
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();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
