← DiffPush

Remove K Digits

Standard Bar Stack and Queues · Monotonic Stack and Queue O(n) · O(n)

The License Plate Trimmer

A DMV system shrinks oversized license plate codes by deleting exactly k digits so the remaining number reads as small as possible. A greedy pass retires any digit that is taller than the digit arriving right after it — each removal buys the biggest possible drop in value — and leftover deletions trim from the tail.

Input: A string num of digits and an integer k, the count of deletions.

Output: Return the smallest possible number as a string, with leading zeros stripped; the empty result prints as "0".

Constraints

Examples

Example 1

Input: {"num":"1432219","k":3}
Output: "1219"
Deleting 4, 3, and the second 2 leaves 1219, the smallest reachable value.

Example 2

Input: {"num":"10200","k":1}
Output: "200"
Removing the 1 leaves 0200; stripping the leading zero prints 200.

Solve this in your browser →

Also on LeetCode ↗