Imagine you have a number displayed on a digital screen, but the digits must never decrease from left to right. If the number doesn't meet this rule, you want to find the largest number less than or equal to it that does.
Given a non-negative integer n, find the largest number less than or equal to n with monotone increasing digits. A number has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.
0 <= n <= 10^9
Edge cases: n = 0 → 0 (smallest number)n = 10 → 9 (single digit fallback)n = 111111111 → 111111111 (all digits same)
def monotoneIncreasingDigits(n: int) -> int:public int monotoneIncreasingDigits(int n)int monotoneIncreasingDigits(int n)function monotoneIncreasingDigits(n)
def monotoneIncreasingDigits(n: int) -> int:
# Write your solution here
pass
class Solution {
public int monotoneIncreasingDigits(int n) {
// Write your solution here
return 0;
}
}
#include <vector>
using namespace std;
int monotoneIncreasingDigits(int n) {
// Write your solution here
return 0;
}
function monotoneIncreasingDigits(n) {
// Write your solution here
}
Common Bugs to Avoid
Wrong: 332Not adjusting digits when input is not monotone increasing.✅ Implement a right-to-left scan to detect decreases and adjust digits accordingly.
Wrong: 10Returning input without checking monotonicity or adjusting digits.✅ Check for monotonicity and decrement digits when violation found, setting trailing digits to 9.
Wrong: 1000Failing to handle leading zeros after decrementing the first digit.✅ After decrementing a digit, set all trailing digits to 9 to avoid leading zeros.
Wrong: 2999Fixing only first violation without propagating decrements leftwards.✅ Iterate leftwards repeatedly until all digits are monotone increasing.
Wrong: 1234321Off-by-one error in decrementing digit or setting trailing digits.✅ Decrement digit at violation index and set all digits to the right to 9.