Link: 402. Remove K Digits - Medium
Track: NeetCode150
Question
Restate the problem
- Given string
numthat represents a non-negative integer (like"1432219") and an integerk - Return the answer as a string, and it must not have leading zeros
- remove exactly
kdigits, 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 > 0andstack[-1] > ch, pop the stack (remove that larger digit), decrementk. - 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
lstriponly works onstr
Jan-22-2026 Solved w bug, took too long time
digital stringcan compare- use
whileto deal with stack str.join()works with any iterable of stringslstrip()only work with strings, to eliminate'0'