Problem
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 10^9 + 7.
Examples
Example 1:
| |
Example 2:
| |
Solution
Method 1 - Using DP
Here is the approach:
- Sorting Input: First, sort the array to process smaller values first.
- Dynamic Programming: Use a hashmap (
dp) wheredp[x]represents the number of binary trees with root valuex. Initially, each integer is considered to have one tree where the integer itself is the root node (leaf tree). - Traversal: Iterate through each value in the array and calculate the number of trees it can represent as roots:
- For each integer
x, loop through every possible left childl(whereldividesxevenly). - Calculate the right child (
r) asx / l. - If both
landrexist in the array, multiply the count of trees rooted atlandr, then add this count todp[x].
- For each integer
- Result: Sum all values in
dpmodulo (10^9 + 7).
Code
| |
| |
Complexity
- Time:
O((n^2 + n log n), wherenis the size of the array.O(n log n)for sorting.O(n^2)for nested loops, since for each value we loop through possible left children.
- Space:
O(n)fordphashmap.