Monotone Increasing Digits LeetCode solution in Python

1
# Runtime: 43 ms (Top 69.04%) | Memory: 13.9 MB (Top 20.57%)
2
class Solution:
3
def monotoneIncreasingDigits(self, n: int) -> int:
4
num = list(str(n))
5
for i in range(len(num) - 1):
6
# Step1: When don't meet the condition, num[i]-=1 and repalce all num left into '9' and directly return
7
# However, there is the case that num[i-1]==num[i], which will make num[i]-1<num[i-1]
8
# So, traverse back to find the num that its num[i-1] != num[i](to make sure num[i-1]<=num[i]-1), then do step1 and return
9
if num[i] > num[i + 1]:
10
while i >= 1 and num[i - 1] == num[i]:
11
i -= 1
12
num[i] = chr(ord(num[i]) - 1)
13
return int("".join(num[: i + 1] + ["9"] * (len(num) - i - 1)))
14
return n

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0