Algorithm
Problem Name: 823. Binary Trees With Factors
Given an array of unique integers, arr
, where each integer arr[i]
is strictly greater than 1
.
We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children.
Return the number of binary trees we can make. The answer may be too large so return the answer modulo 109 + 7
.
Example 1:
Input: arr = [2,4]
Output: 3
Explanation: We can make these trees: [2], [4], [4, 2, 2]
Example 2:
Input: arr = [2,4,5,10]
Output: 7
Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2]
.
Constraints:
1 <= arr.length <= 1000
2 <= arr[i] <= 109
- All the values of
arr
are unique.
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
class Solution {
private final int MOD = 1_000_000_007;
public int numFactoredBinaryTrees(int[] arr) {
int n = arr.length;
Arrays.sort(arr);
long[] dp = new long[n];
Arrays.fill(dp, 1);
Map < Integer, Integer> indexMap = new HashMap<>();
for (int i = 0; i < n; i++) {
indexMap.put(arr[i], i);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
if (arr[i] % arr[j] == 0) {
int right = arr[i] / arr[j];
if (indexMap.containsKey(right)) {
dp[i] = (dp[i] + dp[j] * dp[indexMap.get(right)]) % MOD;
}
}
}
}
long result = 0;
for (long count : dp) {
result += count;
}
return (int) (result % MOD);
}
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const numFactoredBinaryTrees = function(A) {
const mod = 10 ** 9 + 7
let res = 0
A.sort((a, b) => a - b)
const dp = {}
for(let i = 0; i < A.length; i++) {
dp[A[i]] = 1
for(let j = 0; j < i; j++) {
if(A[i] % A[j] === 0 && dp.hasOwnProperty(Math.floor( A[i] / A[j]))) {
dp[A[i]] = (dp[A[i]] + dp[A[j]] * dp[Math.floor(A[i] / A[j])]) % mod
}
}
}
for(let el of Object.values(dp)) res = (res + el) % mod
return res
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
class Solution:
def numFactoredBinaryTrees(self, A):
"""
:type A: List[int]
:rtype: int
"""
A.sort()
nums, res, trees, factors = set(A), 0, {}, collections.defaultdict(set)
for i, num in enumerate(A):
for n in A[:i]:
if num % n == 0 and num // n in nums: factors[num].add(n)
for root in A:
trees[root] = 1
for fac in factors[root]: trees[root] += trees[fac] * trees[root // fac]
return sum(trees.values()) % ((10 ** 9) + 7)
Copy The Code &
Try With Live Editor
Input
Output