All problems
0142MediumStringStackGreedyMonotonic Stack

Trim the Freight Code

Tracked in this browser only
Write code

Trains the technique from

LeetCode 402Remove K Digits

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A freight terminal stamps every pallet with a routing code, handed to you as the digit string num. Before the pallet is re-stamped, the terminal is allowed to erase exactly k of the digit positions. Whatever survives keeps the left-to-right arrangement it already had; surviving digits are never rearranged.

Pick the positions to erase so the re-stamped code reads as the lowest whole number that any legal erasure can produce, and hand that code back as a string. Zeros sitting in front of the first non-zero survivor are dropped when the code is stamped. Should the erasure consume every position, the terminal stamps "0".

Examples

Example 1

Input
num = "4297", k = 2
Output
"27"

Erasing the 4 and the 9 leaves 2 followed by 7. No other pair of survivors reads lower than 27.

Example 2

Input
num = "1122", k = 1
Output
"112"

The digits never step down, so the cheapest erasure is the rightmost position.

Example 3

Input
num = "70081", k = 3
Output
"0"

Holding on to the two zeros stamps a value of zero once the front zero is dropped.

Constraints

  • 1 <= k <= num.length <= 10^5
  • num is made up of digit characters only.
  • num carries no zero in front unless it is the lone digit 0.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def remove_kdigits(num: str, k: int) -> str:
Java
public String removeKdigits(String num, int k)
September 7
Apply