Problem 596191 · medium · Level 05 Advanced Algorithms & Graphs

The Superstitious Ticket Seller

greedy · digits

A superstitious ticket seller only hands out tidy numbers, whose decimal digits never go down from left to right (such as 1188 or 7). The ticket counter has reached n. Return the largest tidy number that is not above n.

Examples

Input:  n = 5542
Output: 4999
Input:  n = 1379
Output: 1379
Explanation: 1379 is already tidy.
Input:  n = 1050
Output: 999

Constraints

  • 0 <= n <= 10**18
  • Target complexity: O(d) where d is the number of digits.

Goals

  • Find the first place where the digits stop being non-decreasing
  • Decrement a digit and fill everything after it with 9s
  • Propagate the fix leftwards when the decrement breaks an earlier pair
Starting Python…