310. Remove K Digits to Create Smallest Possible Number
Remove K Digits to Create Smallest Possible Number
Given a non-negative integer num represented as a string, remove exactly k digits while keeping the remaining digits in their original order. Return the smallest possible number.

Method Signature

String removeKdigits(String num, int k)
  • num is the non-negative integer represented as a string.
  • k is the exact number of digits to remove.
  • Return the smallest number that can be formed after the removals.

Output Rules

  • The relative order of the remaining digits must not change.
  • Remove all leading zeroes from the result.
  • Return "0" if every digit is removed or the remaining digits represent zero.

Constraints

  • 1 ≤ num.length() ≤ 10,001
  • 0 ≤ k ≤ num.length()
  • num contains only digits from '0' to '9'.
  • num has no leading zeroes unless num is "0".

Examples

Example 1

removeKdigits(num = "7650281", k = 3)
Output: "281"
Removing 7, 6, and 5 produces the smallest possible result.

Example 2

removeKdigits(num = "10045", k = 1)
Output: "45"
Removing 1 leaves "0045", whose leading zeroes are removed.

Example 3

removeKdigits(num = "9876", k = 2)
Output: "76"
Removing the first two digits gives the smallest possible remaining number.

Example 4

removeKdigits(num = "5000", k = 2)
Output: "0"
The smallest remaining value consists only of zeroes, so the result is normalized to "0".


Please use Laptop/Desktop or any other large screen to add/edit code.