KatInterview

Find the Largest Non-Decreasing Integer Below N

Greedy & IntervalsModel answer
MediumModel answerGreedy & Intervalsgreedymath-bitsstrings

Last 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 10 decrease (1 > 0). The highest non-decreasing integer x <= 10 is 9.

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 3 is greater than 2. Decrementing 3 to 2 locally gives 329, which still decreases (3 > 2). Backtracking to the start of the identical digit sequence yields 299.

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.