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
Binary Trees With Factors INPUT Array of unique integers 2 4 arr = [2, 4] Properties: - All values > 1 - Each can be used multiple times - Parent = Left child * Right child Note: 4 = 2 * 2 (valid factor pair) ALGORITHM STEPS 1 Sort Array [2, 4] (already sorted) 2 Initialize DP dp[2]=1, dp[4]=1 3 Find Factor Pairs For 4: check if 4/j in set DP Calculation: dp[2] = 1 (leaf only) dp[4] = 1 + dp[2]*dp[2] dp[4] = 1 + 1*1 = 2 4 Sum All dp Values Total = dp[2] + dp[4] Total = 1 + 2 = 3 FINAL RESULT Tree 1: 2 Tree 2: 4 Tree 3: 4 2 2 (4 = 2 * 2) Output: 3 3 valid binary trees OK - Verified Key Insight: Use Dynamic Programming with sorted array. For each number n, find all pairs (i,j) where i*j=n and both i and j exist in array. dp[n] = 1 (itself) + sum of dp[i]*dp[j] for all valid pairs. Time: O(n^2), Space: O(n) TutorialsPoint - Binary Trees With Factors | Optimal Solution (Dynamic Programming)
Asked in
Google 15 Amazon 12 Facebook 8
32.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen