You are given an array arr of distinct integers, each larger than 1. Build binary trees whose node values come from arr; a value may be used as often as you like. Every node that has children must have exactly two, and its value must equal the product of its two children.
Count how many different trees can be built. A single node is a tree, and swapping the left and right child gives a different tree. Return the count modulo 1,000,000,007.
Example 1
Input: arr = [3, 9] Output: 3 Why: 3 alone, 9 alone, and 9 with children 3 and 3
2 more examples and the constraints
Example 2
Input: arr = [6, 2, 12, 3] Output: 12 Why: 1 tree for 2, 1 for 3, 3 for 6 and 7 for 12
Example 3
Input: arr = [5, 7] Output: 2 Why: 35 is not in arr, so each number stands alone
Constraints
- 1 ≤ arr.length ≤ 1,000
- 2 ≤ arr[i] ≤ 1,000,000,000
- All values in arr are different
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion with a memoO(n²)
- Sort, then build upO(n²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 1,000 numbers | Verdict |
|---|---|---|---|
| Recursion with a memo | O(n²) | Passes; recursion overhead | |
| Sort, then build up | O(n²) | Best; stops at a ≥ x |
n = length of arr. Without the memo, the recursion is exponential.
Edge cases to test
- One number. [17] has exactly one tree.
- A square. For [2, 4], the tree 4 → (2, 2) uses 2 twice. Count it once, not twice: a = 2 and x / a = 2 is a single pair.
- Missing partner. In [8, 2], 8 / 2 = 4 is not in arr, so 8 has no children.
- Huge counts. Powers of 2 make the counts explode; take the mod every time and multiply in 64 bits.
Common mistakes
- Multiplying two counts in 32-bit ints (or plain JavaScript numbers), which overflows before the mod.
- Counting only one order of the children; (2, 3) and (3, 2) are different trees.
- Processing roots before their children because the array was not sorted.
How to talk through it
- 1Clarify. Are left and right children ordered? Can a value repeat inside one tree?
- 2Define the subproblem. Let dp[x] be the trees rooted at x. Each factor pair gives dp[a] × dp[x / a] more.
- 3Pick an order. Children are smaller than parents, so sorting makes every dp value ready when needed.
- 4Code it with the mod. Use 64-bit math for the product and a map for the x / a lookup.
- 5Test out loud. Run [3, 9] and [6, 2, 12, 3] by hand.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?