Skip to content

Latest commit

 

History

History
24 lines (19 loc) · 895 Bytes

402.-remove-k-digits.md

File metadata and controls

24 lines (19 loc) · 895 Bytes

402. Remove K Digits

  • Medium
  • Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.

Analysis

How would we do the same thing by hand? The answer is if we see a digit that is smaller than the previous number, we delete the previous one, and we keep on doing that until we have removed k digits. The solution below uses the exact same logic.

class Solution:
    def removeKdigits(self, num: str, k: int) -> str:    
        stack = []
        for digit in num:
            while k > 0 and len(stack) > 0 and stack[-1] > digit:
                k -= 1
                stack.pop()  
            stack.append(digit)
        if k > 0:
            stack = stack[:-k]     
        return "".join(stack).lstrip("0") or "0"