KatInterview

679. 24 Game

HardSolutions 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 determine if we can achieve the value 24 by using four given numbers (from cards), the four basic arithmetic operators (+, -, *, /), and parentheses. The key constraints are that division is real division (not integer division), and we must use all four cards. The numbers are small (1 to 9), and the number of cards is fixed at 4. This small, fixed input size strongly suggests an exhaustive search or backtracking algorithm.

Solution

24 Game in Python

class Solution:
    def judgePoint24(self, cards: List[int]) -> bool:
        # Epsilon for float comparisons
        EPSILON = 1e-6
        
        # Convert ints to floats for real division
        nums = [float(c) for c in cards]

        def solve(current_nums):
            # Base case: if one number left, check if it's close to 24
            if len(current_nums) == 1:
                return abs(current_nums[0] - 24) < EPSILON

            # Recursive step: pick any two numbers and perform an operation
            for i in range(len(current_nums)):
                for j in range(i + 1, len(current_nums)):
                    # Create a list of the remaining numbers
                    remaining = [current_nums[k] for k in range(len(current_nums)) if k != i and k != j]
                    
                    a, b = current_nums[i], current_nums[j]
                    
                    # Generate all possible results from one operation on a and b
                    # Addition and multiplication are commutative.
                    # Subtraction and division are not, so check both ways.
                    results = [a + b, a * b, a - b, b - a]
                    if abs(b) > EPSILON:
                        results.append(a / b)
                    if abs(a) > EPSILON:
                        results.append(b / a)

                    # For each result, recurse with the new list
                    for res in results:
                        # Passing a new list `remaining + [res]` handles backtracking implicitly
                        if solve(remaining + [res]):
                            return True
            
            # If no combination works, return false for this path
            return False

        return solve(nums)

24 Game in Java

class Solution {
    private static final double EPSILON = 1e-6;

    public boolean judgePoint24(int[] cards) {
        // Convert int array to a list of doubles for real division
        List<Double> list = new ArrayList<>();
        for (int card : cards) {
            list.add((double) card);
        }
        return solve(list);
    }

    private boolean solve(List<Double> list) {
        // Base case: if there's only one number left, check if it's close to 24
        if (list.size() == 1) {
            return Math.abs(list.get(0) - 24.0) < EPSILON;
        }

        // Recursive step: pick any two numbers and perform an operation
        for (int i = 0; i < list.size(); i++) {
            for (int j = i + 1; j < list.size(); j++) {
                // Create a list of the remaining numbers
                List<Double> nextRoundList = new ArrayList<>();
                for (int k = 0; k < list.size(); k++) {
                    if (k != i && k != j) {
                        nextRoundList.add(list.get(k));
                    }
                }

                double a = list.get(i);
                double b = list.get(j);

                // Perform all possible operations on a and b
                List<Double> results = new ArrayList<>();
                results.add(a + b);       // Addition
                results.add(a * b);       // Multiplication
                results.add(a - b);       // Subtraction
                results.add(b - a);       // Subtraction (reverse)
                if (Math.abs(b) > EPSILON) results.add(a / b); // Division
                if (Math.abs(a) > EPSILON) results.add(b / a); // Division (reverse)

                // For each result, recurse with the new list
                for (double res : results) {
                    nextRoundList.add(res);
                    if (solve(nextRoundList)) {
                        return true;
                    }
                    // Backtrack by removing the last added result
                    nextRoundList.remove(nextRoundList.size() - 1);
                }
            }
        }
        
        // If no combination works
        return false;
    }
}

24 Game in C++

class Solution {
public:
    bool judgePoint24(vector<int>& cards) {
        // Convert int array to a vector of doubles for real division
        vector<double> nums;
        for (int card : cards) {
            nums.push_back(static_cast<double>(card));
        }
        return solve(nums);
    }

private:
    const double EPSILON = 1e-6;

    bool solve(vector<double>& nums) {
        // Base case: if there's only one number left, check if it's close to 24
        if (nums.size() == 1) {
            return abs(nums[0] - 24.0) < EPSILON;
        }

        // Recursive step: pick any two numbers and perform an operation
        for (int i = 0; i < nums.size(); ++i) {
            for (int j = i + 1; j < nums.size(); ++j) {
                // Create a list of the remaining numbers
                vector<double> next_round_nums;
                for (int k = 0; k < nums.size(); ++k) {
                    if (k != i && k != j) {
                        next_round_nums.push_back(nums[k]);
                    }
                }
                
                double a = nums[i];
                double b = nums[j];

                // Perform all possible operations on a and b
                vector<double> results;
                results.push_back(a + b);       // Addition
                results.push_back(a * b);       // Multiplication
                results.push_back(a - b);       // Subtraction
                results.push_back(b - a);       // Subtraction (reverse)
                if (abs(b) > EPSILON) results.push_back(a / b); // Division
                if (abs(a) > EPSILON) results.push_back(b / a); // Division (reverse)
                
                // For each result, recurse with the new list
                for (double res : results) {
                    next_round_nums.push_back(res);
                    if (solve(next_round_nums)) {
                        return true;
                    }
                    // Backtrack
                    next_round_nums.pop_back();
                }
            }
        }
        
        // If no combination works
        return false;
    }
};

24 Game in TypeScript

function judgePoint24(cards: number[]): boolean {
    const EPSILON = 1e-6;
    
    // JS numbers are floats, so just copy the array.
    const nums: number[] = [...cards];

    function solve(currentNums: number[]): boolean {
        // Base case: if one number left, check if it's close to 24
        if (currentNums.length === 1) {
            return Math.abs(currentNums[0] - 24) < EPSILON;
        }

        // Recursive step: pick any two numbers and perform an operation
        for (let i = 0; i < currentNums.length; i++) {
            for (let j = i + 1; j < currentNums.length; j++) {
                // Create a list of the remaining numbers
                const remaining: number[] = [];
                for (let k = 0; k < currentNums.length; k++) {
                    if (k !== i && k !== j) {
                        remaining.push(currentNums[k]);
                    }
                }

                const a = currentNums[i];
                const b = currentNums[j];

                // Generate all possible results from one operation on a and b
                const results: number[] = [a + b, a * b, a - b, b - a];
                if (Math.abs(b) > EPSILON) {
                    results.push(a / b);
                }
                if (Math.abs(a) > EPSILON) {
                    results.push(b / a);
                }

                // For each result, recurse with the new list
                for (const res of results) {
                    // Using spread syntax to create a new array for the recursive call.
                    // This handles backtracking implicitly.
                    if (solve([...remaining, res])) {
                        return true;
                    }
                }
            }
        }

        // If no combination works for this path
        return false;
    }

    return solve(nums);
}

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.