3174. Clear Digits LeetCode Solution
In this guide, you will get 3174. Clear Digits LeetCode Solution with the best time and space complexity. The solution to Clear Digits problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Clear Digits solution in C++
- Clear Digits solution in Java
- Clear Digits solution in Python
- Additional Resources

Problem Statement of Clear Digits
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.
Example 1:
Input: s = “abc”
Output: “abc”
Explanation:
There is no digit in the string.
Example 2:
Input: s = “cb34”
Output: “”
Explanation:
First, we apply the operation on s[2], and s becomes “c4”.
Then we apply the operation on s[1], and s becomes “”.
Constraints:
1 <= s.length <= 100
s consists only of lowercase English letters and digits.
The input is generated such that it is possible to delete all digits.
Complexity Analysis
- Time Complexity:
- Space Complexity:
3174. Clear Digits LeetCode Solution in C++
class Solution {
public:
string clearDigits(string s) {
string ans;
for (const char c : s)
if (isdigit(c))
// Since `ans` only contains non-digit characters, popping the last
// character is equivalent to deleting the closest non-digit character.
ans.pop_back();
else
ans += c;
return ans;
}
};
/* code provided by PROGIEZ */
3174. Clear Digits LeetCode Solution in Java
class Solution {
public String clearDigits(String s) {
StringBuilder sb = new StringBuilder();
for (final char c : s.toCharArray())
if (Character.isDigit(c))
// Since `sb` only contains non-digit characters, popping the last
// character is equivalent to deleting the closest non-digit character.
sb.setLength(sb.length() - 1);
else
sb.append(c);
return sb.toString();
}
}
// code provided by PROGIEZ
3174. Clear Digits LeetCode Solution in Python
class Solution:
def clearDigits(self, s: str) -> str:
ans = []
for c in s:
if c.isdigit():
# Since `ans` only contains non-digit characters, removing the last
# character is equivalent to deleting the closest non-digit character.
ans.pop()
else:
ans.append(c)
return ''.join(ans)
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.