Find the Largest Non-Decreasing Integer Below N
Greedy & IntervalsModel answerLast updated
Find the maximum integer less than or equal to n whose decimal digits do not decrease from left to right.
An integer has non-decreasing digits if every adjacent pair of decimal digits satisfies digits[i] <= digits[i + 1] when read from left to right.
Given a non-negative integer n, compute the largest integer x such that x <= n and the digits of x are in non-decreasing order.
Function Signature
def largest_non_decreasing_number(n: int) -> int:
pass
Constraints
0 <= n <= 10^9
Examples
Example 1:
- Input:
n = 10 - Output:
9 - Explanation: The digits of
10decrease (1 > 0). The highest non-decreasing integerx <= 10is9.
Example 2:
- Input:
n = 1234 - Output:
1234 - Explanation: The digits are already non-decreasing (
1 <= 2 <= 3 <= 4).
Example 3:
- Input:
n = 332 - Output:
299 - Explanation: At index 1, digit
3is greater than2. Decrementing3to2locally gives329, which still decreases (3 > 2). Backtracking to the start of the identical digit sequence yields299.
Hints
Hint 1
Scan from left to right to locate the first pair of adjacent digits where digits[i] > digits[i + 1].
Hint 2
Decrements cannot just be applied to index i if digits[i] is part of a repeated sequence (e.g., in 332, reducing the second 3 to 2 yields 329, which still violates the non-decreasing rule).
Hint 3
Walk backward to the earliest digit in the repeating block, subtract 1 from it, and turn all subsequent digits into 9.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach Walkthrough
To construct the largest valid number less than or equal to n, we want to preserve as many left-most digits of n as possible.
- Locate the first violation: Read the digits from left to right to find the first position
iwheredigits[i] > digits[i + 1]. If no such decrease exists,nis already non-decreasing and can be returned directly. - Handle repeated runs: Decrementing
digits[i]by1and changing all remaining digits to9seems intuitive. However, ifdigits[i]is identical to previous digits (e.g., in332,digits[0] = 3anddigits[1] = 3), simply changingdigits[1]to2creates329, which still violates the non-decreasing property becausedigits[0] > digits[1]. - Backtrack to the head of the run: We must step back to the very first digit in the sequence of equal values (
i = 0for332). - Mutate and pad: Subtraction by 1 is applied at this earliest position, and every position to its right is replaced with
9.
This greedy choice maximizes the value of the most significant digits while ensuring the remainder of the number achieves the maximum possible value (9s).
Python Code
def largest_non_decreasing_number(n: int) -> int:
digits = list(str(n))
length = len(digits)
# Step 1: Scan for the first decreasing adjacent pair
i = 0
while i + 1 < length and digits[i] <= digits[i + 1]:
i += 1
# If no decrease was found, n is already valid
if i == length - 1:
return n
# Step 2: Backtrack over any identical digits to the left
while i > 0 and digits[i - 1] == digits[i]:
i -= 1
# Step 3: Decrement the lead digit of the run and set subsequent digits to '9'
digits[i] = str(int(digits[i]) - 1)
for k in range(i + 1, length):
digits[k] = '9'
return int("".join(digits))
Complexity Analysis
- Time Complexity: $\mathcal{O}(L) = \mathcal{O}(\log_{10} n)$, where $L$ is the number of digits in $n$. We make at most one forward pass to find the violation, one backward pass through duplicate digits, and one forward pass to set
9s. - Space Complexity: $\mathcal{O}(L) = \mathcal{O}(\log_{10} n)$ to store the array of digit characters.
Edge Cases
- Single-digit inputs (
n < 10): Always non-decreasing; returned as-is. - Leading digit reduced to 0 (
n = 100):100converts to099, whichint()parses cleanly to99. - Plateaus with drops (
n = 14443): Scans todigits[3] = 4 > 3, steps back todigits[1] = 4, decrements to3, and pads remaining positions to produce13999.
Common Interview Follow-ups
1. How would you solve this in $\mathcal{O}(1)$ auxiliary space without string conversion?
We can build the solution arithmetically using repunits (numbers consisting purely of ones: $1, 11, 111, \dots$). Any non-decreasing number can be represented as the sum of up to 9 repunits. We greedily add the largest repunit $\le n$ up to 9 times:
def largest_non_decreasing_number_o1(n: int) -> int:
repunit = 1
# Scale repunit to match the digit length of n
temp = n
while temp >= 10:
repunit = repunit * 10 + 1
temp //= 10
res = 0
for _ in range(9):
while repunit > 0 and res + repunit > n:
repunit //= 10
res += repunit
return res
2. What if $n$ is represented as a string with up to $100,000$ digits?
- String-to-integer conversion (
int(s)) becomes inefficient or raises overflow/length restriction errors in languages like Python 3.11+. - The character-array logic remains $\mathcal{O}(L)$ time and can directly output the resulting character array as a string, stripping any single leading
'0'character if present.