Problem Description
Given an array of unique integers arr where each integer is greater than 1, we are to count the number of binary trees we can form such that for every non-leaf node, its value is equal to the product of the values of its two children. Each number in arr can be used multiple times. Return the result modulo 10^9 + 7.
Key Insights
- Sort the array to ensure that when processing an element, all potential factors are already processed.
- Use dynamic programming where each number's count is initially 1 (representing a tree with a single node).
- For every number, check all smaller numbers to see if they can be factors (i.e., if their product gives the current number).
- Use a hash set or dictionary for constant time lookups of numbers in the array.
- When valid factor pairs are found, use the product of the counts representing the number of trees that can form with those factors.
- Take care of the modulo at every step to prevent overflow.
Space and Time Complexity
Time Complexity: O(n^2) in the worst-case where n is the length of arr
Space Complexity: O(n) for storing the dp state and using a dictionary for lookups
Solution
We first sort the array and initialize a dictionary (or equivalent) dp to store the number of trees that can be rooted with each number. Each number starts with a count of 1 since it can form a tree by itself. Then, for each number in the sorted array, iterate over all smaller numbers. If the current number is divisible by the smaller number and the quotient also exists in the dp dictionary, add the product of the two counts to the current dp value. This accounts for trees where the smaller number and its corresponding pair form the children of the current number. Finally, sum all dp values for the answer, taking modulo 10^9 + 7.