Skip to content
DeepForgeby svx
All problems
MediumData Structuresds-092

Remove K Digits with Monotonic Stack

Problem

Remove exactly k digits from a non-negative integer string to make the smallest possible number.

num is a string of digits and k is the number of digits to remove. Use a monotonic increasing stack: while removals remain and the new digit is smaller than the stack top, pop. Then drop remaining digits from the end if needed, and strip leading zeros.

Return the result as a string, or "0" when the result is empty.

Hint

A larger digit followed by a smaller one should be removed first.

Test cases

case 1
in: ["1432219",3]
expected: "1219"
case 2
in: ["10200",1]
expected: "200"
case 3
in: ["10",2]
expected: "0"
case 4
in: ["112",1]
expected: "11"
case 5
in: ["4321",2]
expected: "21"
Starter codePython
def remove_k_digits(num, k):
    # Your code here
    pass

5 test cases · run your code against them in the editor