Binary Trees With Factors - Problem
Imagine you're a tree architect with a unique challenge! You have an array of unique integers arr, where each number is greater than 1. Your task is to build special binary trees where:
- Each non-leaf node's value equals the product of its two children's values
- You can use each number from the array multiple times
- All values in the tree must come from your given array
For example, with [2, 4, 5, 10]:
- You can build a tree with root
10and children2and5(since 2 ร 5 = 10) - You can build a tree with root
4and children both2(since 2 ร 2 = 4)
Goal: Count how many different binary trees you can construct following these rules. Since the answer can be huge, return it modulo 109 + 7.
Input & Output
example_1.py โ Python
$
Input:
[2, 4]
โบ
Output:
3
๐ก Note:
We can make these trees: [2], [4], and [4] with children [2, 2]. The root 4 has two children 2 and 2, and 2 ร 2 = 4.
example_2.py โ Python
$
Input:
[2, 4, 5, 10]
โบ
Output:
7
๐ก Note:
We can make trees: [2], [4], [5], [10], [4 with children 2,2], [10 with children 2,5], and [10 with children 5,2]. Note that [10 with children 2,5] and [10 with children 5,2] are different trees.
example_3.py โ Python
$
Input:
[3, 6]
โบ
Output:
2
๐ก Note:
We can only make single-node trees [3] and [6]. We cannot make [6] with children [3,2] because 2 is not in our array.
Visualization
Tap to expand
Understanding the Visualization
1
Inventory Check
Sort available components [2,4,5,10] by size
2
Single Components
Each component can be a standalone product (4 ways)
3
Assembly Combinations
Find valid combinations: 4=2ร2, 10=2ร5, 10=5ร2
4
Count Total Products
Sum all possible assembly configurations = 7 total
Key Takeaway
๐ฏ Key Insight: Use dynamic programming to avoid recalculating the same subtrees. For each number, the total trees equals 1 (single node) plus the sum of products of subtree counts for all valid factor pairs.
Time & Space Complexity
Time Complexity
O(nยฒ)
Sorting takes O(n log n), then for each of n elements, we check all previous elements for factor pairs
โ Quadratic Growth
Space Complexity
O(n)
DP array to store results for each element
โก Linearithmic Space
Constraints
- 1 โค arr.length โค 1000
- 2 โค arr[i] โค 109
- All values in arr are distinct
- Answer is guaranteed to fit in a 32-bit signed integer after taking modulo 109 + 7
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code