Skip to the code
cf.
+25 XP

#575 Smallest Number After Removing Digits

medium

A coupon generator creates codes from a string of digits digits, then shortens each code by deleting exactly k digits. The remaining digits keep their order, and the shortest-looking code wins: it should be the smallest number possible.

Write smallestAfterRemoving(digits, k) that returns the smallest number, as a string, after removing k digits. Drop leading zeros from the answer, and return "0" if nothing (or only zeros) is left.

Example 1

Input: digits = "1432219", k = 3
Output: "1219"

Remove 4, 3, and one 2 to get 1219.

Example 2

Input: digits = "10200", k = 1
Output: "200"

Removing the 1 leaves 0200, which is 200.

Constraints

  • 1 <= k <= digits.length <= 100000
  • digits contains only 0-9 and has no leading zeros unless it is "0".
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).