LeetCode 3174: Clear Digits — Multiple Approaches Explained
LeetCode 3174: Clear Digits — Multiple Approaches Explained

LeetCode 3174: Clear Digits — Multiple Approaches Explained

Learn How to Solve LeetCode 3174 With 3 Different Approaches in Java — From Brute Force to Optimal

5 views
0
0
Listen to articleAudio version

What's the Problem Really Asking?

Imagine you're editing a text document and every time you type a number, it acts like a backspace key — it deletes itself AND the character just before it. That's exactly what this problem is!

Given a string like "cb34":

  1. 3 deletes b"c4"
  2. 4 deletes c""

Simple idea, right? Let's look at all the ways to solve it.

Here is the problem link-: Leetcode 3174

Approach 1: Using a Stack (Classic & Intuitive)

The Idea

A stack is the most natural fit here. Think of it like a stack of plates:

  1. If the character is a letter → push it onto the stack (add a plate)
  2. If the character is a digit → pop from the stack (remove the top plate, the digit deletes itself too)

At the end, whatever's left on the stack is your answer.

Code

public String clearDigits(String s) {
Stack<Character> st = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9') {
if (!st.empty()) {
st.pop(); // digit eats the closest left non-digit
}
} else {
st.push(c); // letter goes in
}
}
StringBuilder sb = new StringBuilder();
while (!st.empty()) {
sb.append(st.pop());
}
return sb.reverse().toString(); // stack gives reverse order
}

Real Life Analogy

Think of a Jenga tower. Every time a digit appears, it pulls out the topmost block (the closest left letter). At the end, whatever blocks remain standing — that's your result.

Complexity

  1. Time: O(n) — single pass through the string
  2. Space: O(n) — stack can hold up to n characters in worst case (no digits)

Approach 2: StringBuilder as a Stack (Optimal & Clean) ✅

The Idea

This is the smartest approach and the one you already have in your solution. A StringBuilder naturally behaves like a stack:

  1. Append letters to the end
  2. When a digit appears, delete the last character (.deleteCharAt(sb.length() - 1))

No extra data structure needed!

Code

public String clearDigits(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9') {
sb.deleteCharAt(sb.length() - 1); // digit acts as backspace
} else {
sb.append(c); // letter gets added
}
}
return sb.toString();
}

Walkthrough with Example

Let's trace "cb34" step by step:

StepCharacterActionStringBuilder
1cappend"c"
2bappend"cb"
33delete last"c"
44delete last""

Final answer: ""

Another example — "a1b2c3":

StepCharacterActionStringBuilder
1aappend"a"
21delete last""
3bappend"b"
42delete last""
5cappend"c"
63delete last""

Final answer: ""

Complexity

  1. Time: O(n) — one pass, each character processed once
  2. Space: O(n) — StringBuilder storage

Approach 3: Brute Force / Simulation (Beginner-Friendly)

The Idea

Just simulate exactly what the problem says — find the first digit, remove it and its closest left non-digit, repeat.

public String clearDigits(String s) {
StringBuilder sb = new StringBuilder(s);
boolean found = true;
while (found) {
found = false;
for (int i = 0; i < sb.length(); i++) {
if (Character.isDigit(sb.charAt(i))) {
sb.deleteCharAt(i); // delete the digit
if (i > 0) {
sb.deleteCharAt(i - 1); // delete closest left non-digit
}
found = true;
break; // restart the search
}
}
}
return sb.toString();
}

Complexity

  1. Time: O(n²) — for each digit found, we restart scanning from the beginning
  2. Space: O(n) — StringBuilder storage

This works fine for the given constraints (n ≤ 100), but it's not scalable for large inputs.

Approach Comparison

ApproachTimeSpaceCode SimplicityBest For
Brute ForceO(n²)O(n)⭐⭐⭐Understanding the problem
StackO(n)O(n)⭐⭐⭐⭐Interviews (clear intent)
StringBuilderO(n)O(n)⭐⭐⭐⭐⭐Production / Best solution

Key Takeaways

1. Recognize the Stack Pattern Anytime a problem says "delete the closest left element," your brain should immediately scream stack. This pattern appears in many problems like Valid Parentheses, Asteroid Collision, and Backspace String Compare.

2. StringBuilder is a hidden stack In Java, StringBuilder supports append() (push) and deleteCharAt(length-1) (pop). Using it directly instead of a Stack<Character> saves you the overhead of boxing/unboxing characters and the extra reverse step.

3. The problem guarantees all digits can be deleted This means you'll never call deleteCharAt on an empty StringBuilder. In a real interview, you'd still want to add a guard check (if (sb.length() > 0)) to be safe and show defensive coding habits.

Similar Problems to Practice

  1. 844. Backspace String Compare — almost identical concept
  2. 1047. Remove All Adjacent Duplicates In String — same stack pattern
  3. 2390. Removing Stars From a String — stars act as backspace, same idea


Ai Assistant Kas