Binary Trees With Factors - 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 large so return the answer modulo 109 + 7.
Input & Output
Example 1 — Basic Case
$
Input:
arr = [2,4]
›
Output:
3
💡 Note:
We can make these trees: [2] (root 2), [4] (root 4), and [4,2,2] (root 4 with children 2,2). Since 2×2=4, we can build a tree with root 4 and two children of value 2.
Example 2 — More Factors
$
Input:
arr = [2,4,5,10]
›
Output:
7
💡 Note:
Trees with root 2: [2]. Root 4: [4], [4,2,2]. Root 5: [5]. Root 10: [10], [10,2,5], [10,5,2]. Total = 1 + 2 + 1 + 3 = 7 trees.
Example 3 — Single Element
$
Input:
arr = [3]
›
Output:
1
💡 Note:
Only one tree possible: [3] with single node as root.
Constraints
- 1 ≤ arr.length ≤ 1000
- 2 ≤ arr[i] ≤ 109
- All the values of arr are unique
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [2,4] of unique integers > 1
2
Find Factors
Check which numbers can be products: 4 = 2×2
3
Count Trees
Total trees: [2], [4], [4,2,2] = 3
Key Takeaway
🎯 Key Insight: Count all possible binary trees where each non-leaf node equals the product of its children
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code