Monotone Increasing Digits - Problem

An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x ≤ y.

Given an integer n, return the largest number that is less than or equal to n with monotone increasing digits.

Example: For n = 10, the answer is 9 because 10 has digits 1, 0 where 1 > 0, so it's not monotone increasing. The largest monotone increasing number ≤ 10 is 9.

Input & Output

Example 1 — Basic Violation
$ Input: n = 10
Output: 9
💡 Note: 10 has digits [1,0] where 1 > 0, violating monotone property. The largest monotone number ≤ 10 is 9.
Example 2 — Already Monotone
$ Input: n = 1234
Output: 1234
💡 Note: 1234 has digits [1,2,3,4] where 1 ≤ 2 ≤ 3 ≤ 4, so it's already monotone increasing.
Example 3 — Multiple Violations
$ Input: n = 54321
Output: 49999
💡 Note: 54321 violates at position 0 (5>4). Reduce 5→4 and set rest to 9s: 49999.

Constraints

  • 0 ≤ n ≤ 109

Visualization

Tap to expand
Monotone Increasing Digits: Transform 54321 → 4999954321Violation: 5 > 4Fix: Reduce 5→4, Fill rest with 9s49999Monotone: 4 ≤ 9 ≤ 9 ≤ 9 ≤ 9Result: 49999(Largest monotone ≤ 54321)
Understanding the Visualization
1
Input Number
Given number n with potential violations
2
Check Monotone
Find digits where current > next
3
Fix & Maximize
Reduce violating digit, fill rest with 9s
Key Takeaway
🎯 Key Insight: When a digit violates monotone property, reduce it and maximize all following digits with 9s
Asked in
Google 25 Amazon 18 Microsoft 15
32.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen