NeetCode #360LC-402MediumStack
← Back to All Problems#360 · #402 · Remove K Digits(移掉 K 位数字)
📌 Problem Statement & Constraints
Given a non-negative integer as a string
num and an integer k, remove k digits so that the remaining number is the smallest possible, preserving the relative order of the remaining digits. Return the result as a string with no leading zeros (use "0" if the result is empty). Constraints: 1 <= k <= num.length <= 10^5.💡 Core Algorithmic Approaches
- This is the classic "remove digits to minimise" greedy, solved with a monotonically increasing stack.
- For each digit, while the stack top is greater than the current digit and removals remain, pop it -- a larger leading digit is always worse.
- Push the current digit. If removals remain after the scan, they must come off the end (the number is already non-decreasing).
- Finally strip leading zeros; an all-zero result becomes
"0".
💻 Benchmark Python3 Implementation
class Solution:
def removeKdigits(self, num: str, k: int) -> str:
st = []
for d in num:
# pop larger leading digits while we still have removals
while k and st and st[-1] > d:
st.pop()
k -= 1
st.append(d)
if k: # number is already non-decreasing
st = st[:-k] # remove from the end
res = "".join(st).lstrip("0")
return res if res else "0"⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): each digit is pushed once and popped at most once.
💾 Space Complexity
O(n) for the stack.
⚠️ Interview Pitfalls & Follow-ups
- Forgetting the leftover
k: if the digits are already non-decreasing, the removals must come from the end. - Using
>=in the pop condition: removing equal digits is never beneficial, and it can produce a worse result for the same removal count. Use strict>. - Forgetting to strip leading zeros:
"10200"withk = 1gives"200", but"100"withk = 1gives"00", which must become"0". - Returning an empty string: the contract requires
"0".
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Stack Problems
中文速览与面试要点
移掉 K 位数字
给你一个以字符串表示的非负整数 num 和一个整数 k,移除这个数中的 k 位数字,使得剩下的数字最小。请你以字符串形式返回这个最小的数字。约束:1 ≤ k ≤ num.length ≤ 10^5;num 仅由数字组成,且不含任何前导零(除了 0 本身)。
核心要点
- 单调递增栈(标准解) :遍历 num,若栈顶数字大于当前数字且还有删除次数,则弹出栈顶并消耗一次删除机会。
- 为什么这样最小 :从左到右,越靠左的数字权重越大;因此应尽可能让高位更小——当遇到比栈顶更小的数字时,弹掉栈顶(较大者)能让高位变小。
- 剩余删除次数 :遍历结束后若 k 仍大于 0,说明 num 本身是单调不减的,此时删除末尾的 k 位。
- 前导零处理 :用 lstrip("0") 去掉前导零;若结果为空则返回 "0" 。
常见陷阱
- 忘记处理剩余删除次数 :如 num = "12345"、k = 2 时,栈不会弹出任何元素,必须删除末尾 2 位。
- 忘记去前导零 :如 num = "10200"、k = 1 会得到 "0200",应返回 "200"。
- 结果为空时返回空串 :如 num = "10"、k = 2 会得到空串,应返回 "0"。
- 比较用 >= 而非 > :用 > 保证只在严格更小时才弹出,是标准写法;用 >= 会弹出相等的元素,结果仍正确但会浪费删除次数。
- k 大于等于 num 长度 :此时应返回 "0",本解通过 lstrip + 判空处理。
参考实现
class Solution:
def removeKdigits(self, num: str, k: int) -> str:
stack = []
for d in num:
# 栈顶更大且还有删除次数 -> 弹出
while k > 0 and stack and stack[-1] > d:
stack.pop()
k -= 1
stack.append(d)
# 若还有剩余删除次数,删除末尾(此时栈是单调不减的)
if k > 0:
stack = stack[:-k]
# 去掉前导零
res = ''.join(stack).lstrip('0')
return res if res else '0'