Link: 402. Remove K Digits - Medium
Track: NeetCode150

Question

Restate the problem

  • Given string num that represents a non-negative integer (like "1432219") and an integer k
  • Return the answer as a string, and it must not have leading zeros
  • remove exactly k digits, so the resulting number is as small as possible.

Whenever the next digit is smaller than the previous digit, we should remove the previous larger digit (if we still have k removals) to make the number as small as possible.


Method 1
Method 2

Method - Stack

Approach - monotonic increasing stack

  • Use stack to keep digits:
    • Scan digits left → right.
    • While k > 0 and stack[-1] > ch, pop the stack (remove that larger digit), decrement k.
    • Push ch.
  • If k is still > 0 after the scan, remove from the end (stack[:-k]) because the number is already increasing, so the tail digits are the best to delete.
  • Result: res = ''.join(stack).lstrip('0'); if empty return "0"

Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(n)

Edge Case

  • k == len(num), return “0”

Code

class Solution:
    def removeKdigits(self, num: str, k: int) -> str:
        stack = []
        for char in num:
            while stack and stack[-1] > char and k != 0:
                k -= 1
                stack.pop()
            
            stack.append(char)
        
        if k > 0:
            stack = stack[:-k]
 
        tmp = ("").join(stack)
        res = tmp.lstrip('0')
        
        return str(res) if res else "0"   

History

Jan-25-2026 Solved w bug

  • stack = stack[:k] to slice

Jan-24-2026 Solved w bug

  • lstrip only works on str

Jan-22-2026 Solved w bug, took too long time

  • digital string can compare
  • use while to deal with stack
  • str.join() works with any iterable of strings
  • lstrip() only work with strings, to eliminate '0'