class Solution:
    def removeKdigits(self, num: str, k: int) -> str:
        # Using monotonic stack
        mstack = []
        
        for c in num:
            while k > 0 and mstack and mstack[-1] > c:
                mstack.pop()
                k -= 1
 
            mstack.append(c)
        
        # k might not be 0
        mstack = mstack[:len(mstack) - k]
 
        # To remove leading zeroes
        res = "".join(mstack).lstrip("0")
        return res if res else "0"

Complexity

Time:
Space: