Remove K Digits
Real-world version: Trim the Freight CodeThe statement here is our own: the same inputs, outputs and technique.
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 starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def remove_kdigits(num: str, k: int) -> str:public String removeKdigits(String num, int k)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 11 test cases: 11 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Smallest Subsequence of Distinct CharactersReal-world version: Earliest Depot Summary TagMedium
- Remove Duplicate LettersReal-world version: Smallest Distinct LabelMedium
- Valid Parenthesis StringReal-world version: Salvage a Smudged Span TraceMedium
- Using a Robot to Print the Lexicographically Smallest StringReal-world version: Typesetter's RackMedium