Start learning free

LESSON 474 OF 677 · STACK

Remove K Digits

Practice O(n)

You get a string num with the digits of a whole number. You also get a number k.

Delete exactly k digits from num. The other digits keep their order. Return the smallest number you can get this way, as a string.

Drop any leading zeros. If no digits are left, or only zeros, return "0".

 

Example 1:

Input: num = "52918", k = 2
Output: "218"
Explanation: Deleting 5 and 9 leaves 218.
Deleting any other two digits gives a larger number.

Example 2:

Input: num = "30045", k = 1
Output: "45"
Explanation: Deleting 3 leaves "0045".
Without its leading zeros, that is "45".

Example 3:

Input: num = "777", k = 3
Output: "0"
Explanation: All the digits are deleted.
No digits are left, so the answer is "0".

 

Constraints:

  • num has 1 to 10,001 digits.
  • num does not start with 0.
  • k is from 1 to the number of digits in num.
STEP 1 OF 20
    Ctrl + Enter to check