Greedy Algorithms - Remove K Digits (Smallest Number)
The following code attempts to remove k digits from a number string to get the smallest number. Which line contains a subtle bug that causes incorrect results on inputs with leading zeros?
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) # Bug here
return result if result else '0'
