Monotone Increasing Digits — LeetCode 738 Python Solution
- Problem
- #738
- Pattern
- Greedy
- Reading time
- 3 min
- Source
- leetcode.com
The 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.
Example
- Input
- n = 10
- Output
- 9
Python solution
class Solution:
def monotoneIncreasingDigits(self, n: int) -> int:
s = list(str(n))
i = 1
while i < len(s) and s[i - 1] <= s[i]:
i += 1
if i < len(s):
while i and s[i - 1] > s[i]:
s[i - 1] = str(int(s[i - 1]) - 1)
i -= 1
i += 1
while i < len(s):
s[i] = '9'
i += 1
return int(''.join(s))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) |
| Space | O(1) to O(n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 738. Monotone Increasing Digits is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 738. Monotone Increasing Digits?
- LeetCode 738. Monotone Increasing Digits is rated Medium on LeetCode.
- What topics does LeetCode 738. Monotone Increasing Digits cover?
- LeetCode 738. Monotone Increasing Digits is tagged Greedy and Math on LeetCode.