KatInterview

553. Optimal Division

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 us to insert parentheses into a sequence of divisions, nums[0] / nums[1] / ... / nums[n-1], to maximize the final value. The numbers are all positive integers greater than or equal to 2.

Solution

Optimal Division in Python

class Solution:
    def optimalDivision(self, nums: List[int]) -> str:
        n = len(nums)
        
        # If there's only one number, just return it as a string.
        if n == 1:
            return str(nums[0])
        
        # If there are two numbers, the only expression is "num1/num2".
        if n == 2:
            return f"{nums[0]}/{nums[1]}"
        
        # For n > 2, the optimal strategy is X1 / (X2 / X3 / ... / Xn).
        # This maximizes the expression because it becomes (X1 * X3 * X4 * ...) / X2.
        # We can use str.join to create the denominator part.
        denominator = "/".join(map(str, nums[1:]))
        return f"{nums[0]}/({denominator})"

Optimal Division in Java

class Solution {
    public String optimalDivision(int[] nums) {
        int n = nums.length;

        // If there's only one number, just return it as a string.
        if (n == 1) {
            return String.valueOf(nums[0]);
        }

        // If there are two numbers, the only expression is "num1/num2".
        if (n == 2) {
            return nums[0] + "/" + nums[1];
        }

        // For n > 2, the optimal strategy is X1 / (X2 / X3 / ... / Xn).
        // This maximizes the expression because it becomes (X1 * X3 * X4 * ...) / X2.
        StringBuilder sb = new StringBuilder();
        sb.append(nums[0]).append("/(");
        for (int i = 1; i < n; i++) {
            sb.append(nums[i]);
            if (i < n - 1) {
                sb.append("/");
            }
        }
        sb.append(")");

        return sb.toString();
    }
}

Optimal Division in C++

class Solution {
public:
    string optimalDivision(vector<int>& nums) {
        int n = nums.size();
        
        // If there's only one number, just return it as a string.
        if (n == 1) {
            return to_string(nums[0]);
        }
        
        // If there are two numbers, the only expression is "num1/num2".
        if (n == 2) {
            return to_string(nums[0]) + "/" + to_string(nums[1]);
        }
        
        // For n > 2, the optimal strategy is X1 / (X2 / X3 / ... / Xn).
        // This maximizes the expression because it becomes (X1 * X3 * X4 * ...) / X2.
        string result = to_string(nums[0]) + "/(";
        for (int i = 1; i < n; ++i) {
            result += to_string(nums[i]);
            if (i < n - 1) {
                result += "/";
            }
        }
        result += ")";
        
        return result;
    }
};

Optimal Division in TypeScript

function optimalDivision(nums: number[]): string {
    const n = nums.length;

    // If there's only one number, just return it as a string.
    if (n === 1) {
        return `${nums[0]}`;
    }

    // If there are two numbers, the only expression is "num1/num2".
    if (n === 2) {
        return `${nums[0]}/${nums[1]}`;
    }

    // For n > 2, the optimal strategy is X1 / (X2 / X3 / ... / Xn).
    // This maximizes the expression because it becomes (X1 * X3 * X4 * ...) / X2.
    // We use slice to get the denominator part and join them with '/'.
    const denominator = nums.slice(1).join('/');
    return `${nums[0]}/(${denominator})`;
};

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.