Remove K Digits

Problem Id: 402 Difficulty: Medium


Intuition

Solution


class Solution:
    def removeKdigits(self, num: str, k: int) -> str:
        ans = ""
        while True:
            if k == len(num):
                break
            elif k == 0:
                ans += num
                break
            choice = str(min(int(c) for c in num[:k+1]))
            i = num.index(choice)
            k -= i
            ans += num[i]
            num = num[i+1:]

        i = 0
        while i < len(ans) and ans[i] == '0':
            i += 1
        ans = ans[i:]

        if not ans:
            return '0'
        return ans