KatInterview

738. Monotone Increasing Digits

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the largest integer less than or equal to a given integer n that has "monotone increasing digits". This property means that for any pair of adjacent digits x and y in the number, x <= y must hold. For example, 123, 447, and 8 are monotone increasing, while 321, 10, and 434 are not.

Solution

Monotone Increasing Digits in Python

class Solution:
    def monotoneIncreasingDigits(self, n: int) -> int:
        # Convert the integer to a list of its character digits for mutability.
        s = list(str(n))
        L = len(s)
        # This variable will store the index from which all following digits should be '9'.
        # Initialized to L, implying no changes initially.
        nine_start_idx = L

        # Iterate from right to left (from the second to last digit to the first).
        for i in range(L - 2, -1, -1):
            # If a digit is greater than the one to its right, it's a violation.
            if s[i] > s[i+1]:
                # To fix this, decrement the current digit.
                s[i] = str(int(s[i]) - 1)
                # Mark the starting position for '9's. Any violation further to the left
                # will update this to an earlier index.
                nine_start_idx = i + 1

        # Set all digits from nine_start_idx to the end to '9'.
        for i in range(nine_start_idx, L):
            s[i] = '9'
        
        # Join the list of characters to a string and convert back to an integer.
        return int("".join(s))

Monotone Increasing Digits in Java

class Solution {
    public int monotoneIncreasingDigits(int n) {
        // Convert the integer to a character array for easy manipulation of digits.
        char[] s = String.valueOf(n).toCharArray();
        int len = s.length;
        // This variable will store the index from which all following digits should be set to '9'.
        // Initialize to len, indicating no changes are needed initially.
        int nineStartIdx = len;

        // Iterate from right to left (from the second to last digit to the first).
        for (int i = len - 2; i >= 0; i--) {
            // If a digit is greater than the one to its right, it violates the monotone property.
            if (s[i] > s[i + 1]) {
                // To fix the violation, we decrement the current digit.
                // Character arithmetic `s[i]--` works here.
                s[i]--;
                // Mark the starting position for '9's. All digits from here onwards
                // will be set to '9' to get the largest possible monotone number.
                nineStartIdx = i + 1;
            }
        }

        // Set all digits from nineStartIdx to the end of the array to '9'.
        for (int i = nineStartIdx; i < len; i++) {
            s[i] = '9';
        }

        // Convert the character array back to a string and then to an integer.
        return Integer.parseInt(new String(s));
    }
}

Monotone Increasing Digits in C++

class Solution {
public:
    int monotoneIncreasingDigits(int n) {
        // Convert the number to a string to easily manipulate individual digits.
        string s = to_string(n);
        int len = s.length();
        // This variable will store the index from which all following digits should be set to '9'.
        // It's initialized to len, meaning no changes are needed initially.
        int nine_start_idx = len;

        // Iterate from right to left (second to last digit to the first).
        for (int i = len - 2; i >= 0; i--) {
            // If a digit is greater than the one to its right, it violates the monotone property.
            if (s[i] > s[i + 1]) {
                // To fix the violation, we must decrease the current digit.
                s[i]--;
                // Mark the starting position for '9's. All digits from this position onwards
                // must become '9' to form the largest possible monotone number.
                nine_start_idx = i + 1;
            }
        }

        // Change all digits from nine_start_idx to the end to '9'.
        for (int i = nine_start_idx; i < len; i++) {
            s[i] = '9';
        }

        // Convert the modified string back to an integer.
        return stoi(s);
    }
};

Monotone Increasing Digits in TypeScript

function monotoneIncreasingDigits(n: number): number {
    // Convert the number to an array of string digits for mutability.
    let s = String(n).split('');
    const L = s.length;
    // This variable stores the index from which all subsequent digits should be '9'.
    // Initialized to L, meaning no changes needed initially.
    let nineStartIdx = L;

    // Iterate from right to left (from the second to last digit to the first).
    for (let i = L - 2; i >= 0; i--) {
        // If a digit is greater than the one to its right, it violates the property.
        if (s[i] > s[i + 1]) {
            // To fix the violation, decrement the current digit.
            s[i] = String(Number(s[i]) - 1);
            // Mark the starting position for '9's. All digits from this position
            // will be set to '9' to maximize the number.
            nineStartIdx = i + 1;
        }
    }

    // Set all digits from nineStartIdx to the end of the array to '9'.
    for (let i = nineStartIdx; i < L; i++) {
        s[i] = '9';
    }

    // Join the array of digits into a string and convert it back to a number.
    return Number(s.join(''));
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.