Grokking the Coding Interview: Patterns for Coding Questions
0% completed
Solution: Remove K Digits
.....
.....
.....
Like the course? Get enrolled and start learning!
A
Anonymous
· 2 years ago
class Solution: def removeKdigits(self, num: str, k: int) -> str: count = 0 stack = [] for d in num: # while the number is smaller that the top of stack keep popping while count < k and len(stack) > 0 and int(d) < int(stack[-1]): stack.pop() count += 1 # don't insert 0 if the stack is empty otherwise insert if len(stack) == 0: if int(d) > 0: stack.append(d) else: stack.append(d) # remaining number that needs to be popped out to meet k while len(stack) > 0 and count < k: count += 1 stack.pop() result = "".join(stack) # empty string mean
Reading Progress
0%