All problems

Problem 140

Remove K Digits

Medium · 20 pts · String, Stack, Greedy, Monotonic Stack

Problem

You are given a non-negative integer as a string of digits and a number K. Remove exactly K digits so that the remaining digits, in their original order, form the smallest possible number. Print it without leading zeros, and print 0 if no digits remain or only zeros remain. Greedy with a stack: go through the digits, and while K > 0 and the previous kept digit is larger than the current digit, remove the previous digit. Removing a larger digit earlier in the number always makes it smaller. If removals are left over at the end, remove them from the back.

Input

First line: the number (digits only). Second line: integer K.

Output

Print the smallest possible number.

Constraints

1 <= K <= length <= 100000; the number has no leading zeros except '0' itself

Example input

1432219
3

Example output

1219

Explanation

For 1432219 with K = 3: 4 is removed because 3 is smaller, 3 because 2 is smaller, and the second 2 because 1 is smaller. The remaining digits are 1219.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Gas Station Next: Maximum Depth of Binary Tree