FastPrepRemove K Digits

Remove K Digits

Procol logoProcol● MediumFULLTIMEPHONE SCREEN

Problem statement

You are given a string num that holds a non-negative integer, and an integer k.

Remove exactly k digits from num. The digits you keep stay in their original order. Choose the digits to remove so that the number left is as small as possible.

Return that number as a string without leading zeros. If no digits are left, or only zeros are left, return "0".

Function

removeKdigits(num: String, k: int) → String

Examples

Example 1

num = "4325043"k = 3return = "2043"

Remove 4, then 3, then 5. Each of them is larger than the digit right after it. The digits left are 2, 0, 4, 3, which form 2043. No other choice of three digits gives a smaller number.

Example 2

num = "30200"k = 1return = "200"

Removing the 3 leaves 0200. Leading zeros are dropped, so the answer is "200".

Example 3

num = "5337"k = 2return = "33"

Removing 5 leaves 337. From here the digits never go down, so the best last removal is the final digit 7. That leaves "33".

Example 4

num = "100"k = 1return = "0"

Removing the 1 leaves 00. Only zeros are left, so the answer is "0".

Constraints

  • 1 <= num.length <= 10^5
  • 1 <= k <= num.length
  • num consists of digits only.
  • num has no leading zeros, except when num is "0".

More Procol problems

See Procol hiring insights
Saved
public String removeKdigits(String num, int k) {
    // Write your solution here.
}
Checking account…