402. Remove K Digits

https://leetcode.com/problems/remove-k-digits/

class Solution:
    def removeKdigits(self, num: str, k: int) -> str:
        stack = []
        for i in num:
            while stack and k > 0 and stack[-1] > i:
                stack.pop()
                k-=1
            stack.append(i)
        while k > 0:
            stack.pop()
            k-=1
        if len(stack) == 0:
            return "0"
        return str(int("".join(stack)))

Last updated

Was this helpful?