Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created February 10, 2025 15:28
Show Gist options
  • Save Ifihan/f2287629c05b606bf2eaf3e2bfbd44ee to your computer and use it in GitHub Desktop.
Save Ifihan/f2287629c05b606bf2eaf3e2bfbd44ee to your computer and use it in GitHub Desktop.
Clear Digits

Question

Approach

This was uqite straightforward as I used a stack to track and remove the characters. I then iterated through the string character by character. If the character was a digit, I removed the closest non-digit character to its left by popping the top element from the stack (if it wasn’t empty). If the character was not a digit, I simply added it to the stack.

At the end of the process, the stack contained only the remaining characters. I then joined them together to form the final result and returned it.

Implementation

class Solution:
    def clearDigits(self, s: str) -> str:
        stack = []

        for i in s:
            if i.isdigit():
                if stack:
                    stack.pop()
            else:
                stack.append(i)
                
        return "".join(stack)

Complexities

  • Time: O(n)
  • Space: O(n)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment