#738

Monotone Increasing Digits

Medium
MathGreedyGreedyDigit Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution involves modifying the digits of n directly to ensure they are monotone increasing. This approach is efficient because it avoids unnecessary checks and directly constructs the result.

⚙️

Algorithm

4 steps
  1. 1Step 1: Convert the number n to a string to access each digit.
  2. 2Step 2: Identify the first position where a digit is greater than the next digit.
  3. 3Step 3: Decrease the digit at this position by 1 and set all subsequent digits to 9.
  4. 4Step 4: Ensure that the modified number is still less than or equal to n.
solution.py16 lines
1# Full working Python code
2
3def monotoneIncreasingDigits(n):
4    s = list(str(n))
5    length = len(s)
6    mark = length
7
8    for i in range(length - 1, 0, -1):
9        if s[i] < s[i - 1]:
10            mark = i
11            s[i - 1] = str(int(s[i - 1]) - 1)
12
13    for i in range(mark, length):
14        s[i] = '9'
15
16    return int(''.join(s))

Complexity note: The time complexity is O(n) because we traverse the digits of n a couple of times, and the space complexity is O(n) due to the storage of the digits in an array.

  • 1Understanding how to manipulate digits directly can lead to more efficient solutions.
  • 2Recognizing patterns in digit comparisons is crucial for optimization.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.