> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Monotone Increasing Digits Python Solution

> Tested Python solution for LeetCode 738 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 738, [Medium](/catalog/medium). Topics: [Math](/catalog/topics/math), [Greedy](/catalog/topics/greedy). [View on LeetCode](https://leetcode.com/problems/monotone-increasing-digits/description/).

Generate this problem as a practice environment: tested reference solution, 20 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 738   # by problem number
lcpy gen -s monotone_increasing_digits   # by problem name
```

## 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.

### Examples

```
Input: n = 10
Output: 9
```

```
Input: n = 1234
Output: 1234
```

```
Input: n = 332
Output: 299
```

### Constraints

* `0 <= n <= 10^9`

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/monotone_increasing_digits/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/monotone_increasing_digits/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(d) where d is the number of digits in n
    # Space: O(d)
    def monotone_increasing_digits(self, n: int) -> int:
        digits = list(str(n))
        for i in range(len(digits) - 1):
            if digits[i] > digits[i + 1]:
                while i > 0 and digits[i - 1] == digits[i]:
                    i -= 1
                digits[i] = str(int(digits[i]) - 1)
                for j in range(i + 1, len(digits)):
                    digits[j] = "9"
                break
        return int("".join(digits))
```

## Complexity

| Time | Space |
| - | - |
| O(d) where d is the number of digits in n | O(d) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.