DDSA Solutions

3174. Clear Digits

Time: O(n)
Space: O(n)

Problem Overview

Each digit character removes the closest non-digit to its left (if any).

Advertisement

Intuition

Each digit character removes the closest non-digit to its left (if any). Scan left to right with a stack: push non-digits, pop one character when you see a digit. Remaining stack is the answer — digits themselves are never kept.

Algorithm

  1. 1Stack<char> st.
  2. 2For each character c:
  3. 3If c is a digit and st not empty: pop once.
  4. 4Else if c is not a digit: push c.
  5. 5Return string built from stack.

Example Walkthrough

Input: s = "abc"

  1. 1.No digits — nothing removed. Output "abc".

Output: "abc"

Common Pitfalls

  • Digit triggers removal but is not added to result.
  • If stack empty on digit, skip removal.
  • Use char.IsDigit or compare to 0-9 range.
3174.cs
C#
// Approach: Stack; remove each digit and the nearest preceding non-digit character.
// Time: O(n) Space: O(n)

public class Solution
{
    public string ClearDigits(string s)
    {
        StringBuilder sb = new StringBuilder();

        foreach (char c in s)
        {
            if (char.IsDigit(c))
            {
                // Since `sb` only contains non-digit characters, popping the last
                // character is equivalent to deleting the closest non-digit character.
                if (sb.Length > 0)
                    sb.Length--;
            }
            else
                sb.Append(c);
        }

        return sb.ToString();
    }
}
Advertisement
Was this solution helpful?

Related Problems