Remove K digits¶

Remove K digits from a integer and maximise the final value¶

The algorithm works as follow:¶
1) if the number of digits to remove is superior to the length of the string just return 0¶
2) Cast the string in list (easier to remove elements) and create an integer i to iterate over the list¶
3) while there are digits to remove and i is not at the end of the list¶
4) if the current digit is greater than the next one delete it and decrease k by 1 also decrease i by 1 (making sure i is non negative), this is mandatory if two successive digits are equivalent and greater than the next one¶
Example: (7756, k=2, i=0, nums[i]=7, nums[i+1]=7, Do nothing), (7756, k=2, i=1, nums[i]=7, nums[i+1]=5, Remove nums[1]=7)¶
Case 1) if we do not decrement i: (756, k=1, i=1, nums[i]=5, nums[i+1]=6, Do nothing) -> Error¶
Case 2) if we decrement i: (756, k=1, i=0, nums[i]=7, nums[i+1]=5, Remove nums[0]=7) -> 56 -> OK¶
5) If k is still positive there are still digits to remove but there are all equals hence remove the last k digits¶
6) Join the list and cast to int to remove leading 0 before recasting to str¶
In [ ]:
def removeKdigits(num: str, k: int) -> str:
    if k >= len(num):
        return "0"

    i, num = 0, list(num)

    while (k > 0) and (i < len(num)-1):
        if (num[i] > num[i+1]):
            _ = num.pop(i)
            i = max(0, i - 1)
            k = k - 1
        else:
            i += 1

    num = str(int("".join(num[:len(num)-k]))) 
    return(num)