KatInterview

397. Integer Replacement

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 minimum number of operations to transform a positive integer n to 1. The allowed operations depend on whether n is even or odd. This can be viewed as finding the shortest path in an implicit graph where numbers are nodes and operations are edges. While standard shortest path algorithms like Breadth-First Search (BFS) would work, the input n can be very large (2^31 - 1), suggesting that a more direct, perhaps greedy, approach would be more efficient in terms of both time and space.

Solution

Integer Replacement in Python

class Solution:
    def integerReplacement(self, n: int) -> int:
        # Python's integers handle arbitrary size, so no overflow issues.
        count = 0
        
        while n > 1:
            count += 1
            if n % 2 == 0: # If n is even
                n //= 2
            else: # If n is odd
                # The special case for n=3, where n-1 is better than n+1.
                # 3 -> 2 -> 1 (2 steps) vs 3 -> 4 -> 2 -> 1 (3 steps).
                if n == 3:
                    # Current step is 3->2 (already counted). Add one more for 2->1.
                    count += 1
                    break
                
                # For other odd numbers, we want to create as many trailing zeros as possible.
                # If n ends in ...11 (binary), n+1 will end in ...00.
                # This corresponds to n % 4 == 3.
                if n % 4 == 3:
                    n += 1
                else:
                # If n ends in ...01 (binary), n-1 will end in ...00.
                # This corresponds to n % 4 == 1.
                    n -= 1
        
        return count

Integer Replacement in Java

class Solution {
    public int integerReplacement(int n) {
        // Use long to handle the edge case n = Integer.MAX_VALUE, where n+1 would overflow.
        long num = n;
        int count = 0;

        while (num > 1) {
            count++;
            if ((num & 1) == 0) { // If num is even, the only choice is to divide by 2.
                num >>>= 1; // Use unsigned right shift for division by 2.
            } else { // If num is odd
                // The special case for n=3, where n-1 is better than n+1.
                // 3 -> 2 -> 1 (2 steps) vs 3 -> 4 -> 2 -> 1 (3 steps).
                if (num == 3) {
                    // Current step is 3->2 (already counted). Add one more for 2->1.
                    count++;
                    break;
                }

                // For other odd numbers, we want to create as many trailing zeros as possible.
                // If num ends in ...11 (binary), num+1 will end in ...00.
                // This corresponds to num % 4 == 3. Bitwise, this is (num & 2) != 0.
                if ((num & 2) != 0) { // Same as (num % 4 == 3)
                    num++;
                } else {
                // If num ends in ...01 (binary), num-1 will end in ...00.
                // This corresponds to num % 4 == 1. Bitwise, this is (num & 2) == 0.
                    num--;
                }
            }
        }

        return count;
    }
}

Integer Replacement in C++

class Solution {
public:
    int integerReplacement(int n) {
        // Use long long to handle the edge case n = 2^31 - 1, where n+1 would overflow.
        long long num = n;
        int count = 0;
        
        while (num > 1) {
            count++;
            if ((num & 1) == 0) { // If num is even, the only choice is to divide by 2.
                num >>= 1;
            } else { // If num is odd
                // The special case for n=3, where n-1 is better than n+1.
                // 3 -> 2 -> 1 (2 steps) vs 3 -> 4 -> 2 -> 1 (3 steps).
                if (num == 3) {
                    // Current step is 3->2 (already counted). Add one more for 2->1.
                    count++; 
                    break;
                }
                
                // For other odd numbers, we want to create as many trailing zeros as possible.
                // If num ends in ...11 (binary), num+1 will end in ...00.
                // This corresponds to num % 4 == 3. Bitwise, this is (num & 2) != 0.
                if ((num & 2) != 0) { // Same as (num % 4 == 3)
                    num++;
                } else {
                // If num ends in ...01 (binary), num-1 will end in ...00.
                // This corresponds to num % 4 == 1. Bitwise, this is (num & 2) == 0.
                    num--;
                }
            }
        }
        
        return count;
    }
};

Integer Replacement in TypeScript

function integerReplacement(n: number): number {
    // JavaScript's number is a 64-bit float, safe for integers up to 2^53 - 1.
    // The max input 2^31 - 1 is well within this range.
    let count = 0;

    while (n > 1) {
        count++;
        if (n % 2 === 0) { // If n is even
            n /= 2;
        } else { // If n is odd
            // The special case for n=3, where n-1 is better than n+1.
            // 3 -> 2 -> 1 (2 steps) vs 3 -> 4 -> 2 -> 1 (3 steps).
            if (n === 3) {
                // Current step is 3->2 (already counted). Add one more for 2->1.
                count++;
                break;
            }
            
            // For other odd numbers, we want to create as many trailing zeros as possible.
            // If n ends in ...11 (binary), n+1 will end in ...00.
            // This corresponds to n % 4 == 3.
            if ((n + 1) % 4 === 0) { // Equivalent to n % 4 === 3
                n++;
            } else {
            // If n ends in ...01 (binary), n-1 will end in ...00.
            // This corresponds to n % 4 == 1.
                n--;
            }
        }
    }

    return count;
};

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.