Stacks and Queues Monotonic stack
215. Remove K Digits
You are given a string num that holds a non-negative integer, one digit per character, and an integer k.
Remove exactly k digits from num so that the number left is as small as possible. Return that number as a
string.
The digits you keep stay in the order they had in num. The number you return has no leading zeros, so if
the digits left are 0450, return "450". If no digits are left, or only zeros, return "0".
Answers are shown in double quotes.
Example 1
Input: num = "4172938", k = 3
"1238"Explanation: Removing the 4, the 7 and the 9 leaves 1238. Removing the three largest digits, 9, 8 and 7, would leave 4123, which is larger.
Example 2
Input: num = "2477", k = 2
"24"Explanation: Removing the two 7s leaves 24. Any choice that keeps a 7 gives a larger number.
Example 3
Input: num = "900", k = 1
"0"Explanation: Removing the 9 leaves 00, which is the number 0. Return "0", not "00".
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ num.length ≤ 1050 ≤ k ≤ num.lengthnumholds only the digits0to9.numhas no leading zeros: it starts with0only when it is"0".
Clarifying questions
What you would ask an interviewer before writing any code.