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 Greedy Approach - Right to Left Fix INPUT Given number: n = 10 1 index 0 0 index 1 Check: Is 1 <= 0 ? NO - Not monotone! 1 > 0 violates rule Input Value n = 10 ALGORITHM STEPS 1 Convert to digits 10 becomes [1, 0] 2 Scan right to left Find first violation 1 0 scan 3 Decrement digit 1 - 1 = 0 0 0 4 Fill 9s after Set all right digits to 9 0 9 = 9 FINAL RESULT Largest monotone number less than or equal to 10 9 Verification: 9 <= 10 ... OK 9 is monotone ... OK Largest possible ... OK Output: 9 Key Insight: When we find a digit greater than its right neighbor, we decrement it and set ALL digits to its right to 9. This greedy approach ensures we get the largest possible monotone number. For n=10: decrement 1 to 0, then set right digit to 9, giving 09 = 9. Time: O(log n) | Space: O(log n) TutorialsPoint - Monotone Increasing Digits | Greedy Right-to-Left Fix Approach
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