- Medium
- Given string num representing a non-negative integer
num
, and an integerk
, return the smallest possible integer after removingk
digits fromnum
.
How would we do the same thing by hand? The answer is if we see a digit that is smaller than the previous number, we delete the previous one, and we keep on doing that until we have removed k digits. The solution below uses the exact same logic.
class Solution:
def removeKdigits(self, num: str, k: int) -> str:
stack = []
for digit in num:
while k > 0 and len(stack) > 0 and stack[-1] > digit:
k -= 1
stack.pop()
stack.append(digit)
if k > 0:
stack = stack[:-k]
return "".join(stack).lstrip("0") or "0"