Call a number monotone increasing when its digits never go down from left to right: each digit is less than or equal to the one after it. For example, 1559 qualifies, but 1549 does not, because 5 is followed by 4.
Given a whole number n, return the largest monotone increasing number that is no bigger than n.
Example 1
Input: n = 4310 Output: 3999 Why: every number from 4000 to 4310 has a digit that drops; 3999 does not
2 more examples and the constraints
Example 2
Input: n = 1559 Output: 1559 Why: its digits already never go down
Example 3
Input: n = 7651 Output: 6999 Why: the first drop is 7 to 6, so lower the 7 and fill the rest with 9s
Constraints
- 0 ≤ n ≤ 1,000,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Build digit by digitO(d²)
- Right-to-left scan with a markerO(d)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n near 1,000,000,000 | Verdict |
|---|---|---|---|
| Build digit by digit | O(d²) | Works; more to explain | |
| Right-to-left scan | O(d) | Best; one pass |
d = number of digits in n (at most 10).
Edge cases to test
- Already monotone. 1559 is returned as it is; no drop means no change.
- A drop that cascades. 4310 needs three fixes in a row: 1, then 3, then 4 are lowered.
- Leading digit becomes 0. 10 gives 09, which is 9; 100 gives 99.
- Equal digits before a drop. 332 → 299: the second 3 is lowered, which forces the first 3 down too.
- Upper limit. 1,000,000,000 gives 999,999,999.
Common mistakes
- Fixing only the first drop from the left, which misses drops created by lowering (3321 must become 2999).
- Filling 9s only right after the last fix found, instead of after the leftmost one.
- Counting down from n one number at a time, which can take about 10⁸ steps.
How to talk through it
- 1Clarify. Is equal allowed between neighbours? Can n be 0? What is the largest n?
- 2Give the slow idea. Count down and test each number; say why it can take about 10⁸ steps.
- 3Find the fix. At a drop, lower the left digit and fill 9s: that is the biggest number below the drop.
- 4Code the scan. Right to left so that cascading drops are caught; track the leftmost fix.
- 5Test out loud. Run 1559, 4310, 10 and 332 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?