Greedy Algorithms - Remove K Digits (Smallest Number)
Consider the following Python code snippet implementing the optimal solution to remove k digits from a number string to get the smallest number. What is the output of
removeKdigits("1432", 2)?
def removeKdigits(num: str, k: int) -> str:
builder = []
for digit in num:
while k > 0 and builder and builder[-1] > digit:
builder.pop()
k -= 1
builder.append(digit)
while k > 0:
builder.pop()
k -= 1
result = ''.join(builder).lstrip('0')
return result if result else '0'
