oneby7

Stacks and Queues Monotonic stack

215. Remove K Digits

Medium

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

Output: "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

Output: "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

Output: "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.

num = "10200", k = 1

Constraints

  • 1 ≤ num.length ≤ 105
  • 0 ≤ k ≤ num.length
  • num holds only the digits 0 to 9.
  • num has no leading zeros: it starts with 0 only when it is "0".

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.