Problem 579666 · hard · Phase 05 Advanced Algorithms & Graphs

Smallest Meter Reading After Erasing

greedy · monotonic stack · strings

A meter shows the digit string reading. A technician must erase exactly k digits (the others keep their order) and wants the remaining number to be as small as possible. Return it as a string without leading zeros; if nothing (or only zeros) remains, return "0".

Examples

Input:  reading = "4290318", k = 3
Output: "318"
Explanation: Erase 4, 2 and 9 to get "0318", which is 318.
Input:  reading = "30020", k = 1
Output: "20"

Constraints

  • 1 <= len(reading) <= 10**5, 0 <= k <= len(reading).
  • reading contains only digits and has no leading zero unless it is "0".
  • Target complexity: O(n) time.

Goals

  • See why a larger digit followed by a smaller one should be erased first
  • Maintain a non-decreasing stack of kept digits
  • Handle leftover erasures, leading zeros and the empty result
Starting Python…