KatInterview

843. Binary Trees With Factors

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 number of binary trees that can be formed from a given set of unique integers arr. The core constraint is that for any non-leaf node, its value must be the product of its children's values. This property, where the solution for a number x depends on the solutions for its factors Y and Z (where X = Y * Z), points towards a Dynamic Programming approach. We need to build up solutions for larger numbers using the solutions for smaller numbers.

Solution

Binary Trees With Factors in Python

class Solution:
    def numFactoredBinaryTrees(self, arr: List[int]) -> int:
        MOD = 10**9 + 7
        n = len(arr)
        
        # Sort the array to process numbers in increasing order.
        # This ensures that when we calculate dp[x], dp values for its factors are already computed.
        arr.sort()
        
        # dp[x] will store the number of trees with root x.
        dp = {}
        
        total_trees = 0
        
        for i in range(n):
            x = arr[i]
            # Each number can be a tree with a single node (leaf).
            count = 1
            
            # Find factors y and z such that y * z = x.
            for j in range(i):
                y = arr[j]
                # Optimization: if y*y > x, then for any subsequent factor y', y' > y, so y'*y' > x.
                # The other factor z=x/y would be smaller than y, and we would have already processed it.
                if y * y > x:
                    break
                
                if x % y == 0:
                    z = x // y
                    # Check if the other factor z exists in arr (and thus in dp map).
                    if z in dp:
                        # If y and z are the same, we have one combination of children.
                        if y == z:
                            count += dp[y] * dp[z]
                        # If y and z are different, we have two permutations: (y,z) and (z,y).
                        else:
                            count += dp[y] * dp[z] * 2
            
            dp[x] = count
            total_trees += count
            
        return total_trees % MOD

Binary Trees With Factors in Java

class Solution {
    public int numFactoredBinaryTrees(int[] arr) {
        long MOD = 1_000_000_007L;
        int n = arr.length;

        // Sort the array to process numbers in increasing order.
        // This ensures that when we calculate dp[x], dp values for its factors are already computed.
        Arrays.sort(arr);

        // dp[x] will store the number of trees with root x.
        Map<Integer, Long> dp = new HashMap<>();

        long totalTrees = 0;

        for (int i = 0; i < n; i++) {
            int x = arr[i];
            // Each number can be a tree with a single node (leaf).
            long count = 1L;

            // Find factors y and z such that y * z = x.
            for (int j = 0; j < i; j++) {
                int y = arr[j];
                // Optimization: if y*y > x, then for any subsequent factor y', y' > y, so y'*y' > x.
                // The other factor z=x/y would be smaller than y, and we would have already processed it.
                if ((long) y * y > x) {
                    break;
                }

                if (x % y == 0) {
                    int z = x / y;
                    // Check if the other factor z exists in arr (and thus in dp map).
                    if (dp.containsKey(z)) {
                        // If y and z are the same, we have one combination of children.
                        if (y == z) {
                            count = (count + dp.get(y) * dp.get(z)) % MOD;
                        } else {
                        // If y and z are different, we have two permutations: (y,z) and (z,y).
                            count = (count + dp.get(y) * dp.get(z) * 2) % MOD;
                        }
                    }
                }
            }
            dp.put(x, count);
            totalTrees = (totalTrees + count) % MOD;
        }

        return (int) totalTrees;
    }
}

Binary Trees With Factors in C++

class Solution {
public:
    int numFactoredBinaryTrees(vector<int>& arr) {
        long MOD = 1e9 + 7;
        int n = arr.size();
        
        // Sort the array to process numbers in increasing order.
        // This ensures that when we calculate dp[x], dp values for its factors are already computed.
        sort(arr.begin(), arr.end());
        
        // dp[x] will store the number of trees with root x.
        unordered_map<int, long> dp;
        
        long total_trees = 0;
        
        for (int i = 0; i < n; ++i) {
            int x = arr[i];
            // Each number can be a tree with a single node (leaf).
            dp[x] = 1;
            
            // Find factors y and z such that y * z = x.
            for (int j = 0; j < i; ++j) {
                int y = arr[j];
                // Optimization: if y*y > x, then for any subsequent factor y', y' > y, so y'*y' > x.
                // The other factor z=x/y would be smaller than y, and we would have already processed it.
                if ((long)y * y > x) {
                    break;
                }
                
                if (x % y == 0) {
                    int z = x / y;
                    // Check if the other factor z exists in arr (and thus in dp map).
                    if (dp.count(z)) {
                        // If y and z are the same, we have one combination of children.
                        if (y == z) {
                            dp[x] = (dp[x] + dp[y] * dp[z]) % MOD;
                        } else {
                        // If y and z are different, we have two permutations: (y,z) and (z,y).
                            dp[x] = (dp[x] + dp[y] * dp[z] * 2) % MOD;
                        }
                    }
                }
            }
            total_trees = (total_trees + dp[x]) % MOD;
        }
        
        return (int)total_trees;
    }
};

Binary Trees With Factors in TypeScript

function numFactoredBinaryTrees(arr: number[]): number {
    const MOD = 1000000007n; // Use BigInt for the modulus
    const n = arr.length;

    // Sort the array to process numbers in increasing order.
    arr.sort((a, b) => a - b);

    // dp[x] will store the number of trees with root x.
    // Use BigInt for counts to prevent overflow, as products can exceed Number.MAX_SAFE_INTEGER
    const dp = new Map<number, bigint>();

    let totalTrees = 0n;

    for (let i = 0; i < n; i++) {
        const x = arr[i];
        // Each number can be a tree with a single node (leaf).
        let count = 1n;

        // Find factors y and z such that y * z = x.
        for (let j = 0; j < i; j++) {
            const y = arr[j];
            // Optimization: if y*y > x, then for any subsequent factor y', y' > y, so y'*y' > x.
            // The other factor z=x/y would be smaller than y, and we would have already processed it.
            if (y * y > x) {
                break;
            }

            if (x % y === 0) {
                const z = x / y;
                // Check if the other factor z exists in arr (and thus in dp map).
                if (dp.has(z)) {
                    const dpY = dp.get(y)!;
                    const dpZ = dp.get(z)!;
                    // If y and z are the same, we have one combination of children.
                    if (y === z) {
                        count = (count + dpY * dpZ) % MOD;
                    } else {
                    // If y and z are different, we have two permutations: (y,z) and (z,y).
                        count = (count + dpY * dpZ * 2n) % MOD;
                    }
                }
            }
        }
        dp.set(x, count);
        totalTrees = (totalTrees + count) % MOD;
    }

    return Number(totalTrees);
}

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.