Nice solution, but would you mind share some thinking processes of how to come up with the solution to look for the peak value. When I first came across this problem, I go into a totally different solution which turns out to be wrong.
If you look at my original post, you'll find ans with length of num.length() - k.
The resize solution is doing exactly the same thing except that it's using s's prefix as ans in my original solution, which is doing it "in place".
Given above, it's clear that s will end up with my ans as its prefix, which is of length num.length() - k. So it is guaranteed that the last k element will be dropped
I made a similar solution at the first time. An AC but slow pattern since we can finish it in one loop instead of K.
def removeKdigits(self, num, k):
for i in range(len(num) - 1):
if num[i] > num[i + 1]:
return num[:i] + num[i+1:]
for i in range(k):
num = shrink(num)
return str(int(num)) if num else "0"
@StefanPochmann As I clarified in other thread if you remove letter in O(1) it is O(|num|). Slice of course is not O(1), so you are right this implementation is not O(|num|). If we represent string as doubly linked list we can do O(|num|).
Your solution with array is better implementation of the same idea.