SDE & MLE Prep

402. Remove K Digits

Problem

num is a non-negative integer as a string. Remove exactly k digits to make the remaining number as small as possible, and return it without leading zeros ("0" if nothing remains).

Example: num = "1432219", k = 3 → "1219"; num = "10200", k = 1 → "200"

Constraints: length ≤ 10⁵.

To minimize the number, a larger digit followed by a smaller one should go. Keep an increasing stack; pop while the top is bigger than the incoming digit and removals remain. Remove leftovers from the end; strip leading zeros.

num 1432219, k=3
1 -> 14 -> 13 (pop 4) -> 12 (pop 3) -> 122 -> 121 (pop 2) -> 1219

Complexity: O(n).

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