Ctrl K

Largest Number With Non-Decreasing Digits

Medium
Call a non-negative integer tidy if its decimal digits never decrease from left to right: each digit is at least the one before it. Given an integer limit, return the largest tidy number that does not exceed limit.
Example 1
limit=4321 → 3999

The digits of 4321 go down. The largest suitable number not above 4321 is 3999.

Example 2
limit=1559 → 1559

The digits 1, 5, 5, 9 never go down, so the number itself is the answer.

Example 3
limit=20 → 19

The digits of 20 go down, and the closest suitable number below it is 19.

Constraints
  • 0 ≤ limit ≤ 10¹⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSmallest Number From Digit Factors MediumOne Digit Swap MediumFewest Guests by Lanyard Color MediumUp or Down for Every Post MediumDouble or Decrement Medium
loading Python…
Input
limit=4321
Expected
3999

Run checks the first 3 tests in your browser. Submit checks all 111 tests on the server, hidden ones included.