This coding problem asks you to find the number of unique binary trees you can build using an array of unique integers. Each node in the tree must have a value from the array, and if a node has children, the value of the node must be equal to the product of its children's values. You can use each integer from the array as many times as you like.
Google frequently uses this problem to test a candidate's ability to identify subproblems within a complex scenario. It’s a perfect candidate for Dynamic Programming (DP) because the number of ways to form a tree with root depends directly on the number of ways to form trees with roots and , where . It tests your ability to handle sorting, counting, and potentially large results (requiring modulo arithmetic).
This problem uses Dynamic Programming (DP) and Sorting. First, sort the array. This ensures that when you process a number, you've already calculated the results for all its possible factors (which must be smaller). Use a Map to store dp[x], the number of ways to form a tree with root x. For each x, iterate through all smaller numbers y in the array. If x % y == 0 and x / y is also in the array, then dp[x] += dp[y] * dp[x / y].
Array: [2, 4, 8]
dp[2] = 1 (just the node 2).dp[4] = 1 (node 4 itself) + dp[2] * dp[2] = 1 + 1 = 2.dp[8] = 1 (node 8 itself) + dp[2] * dp[4] + dp[4] * dp[2] = 1 + 2 + 2 = 5.
Total trees = 1 + 2 + 5 = 8.One frequent mistake is forgetting to add the "single node" case (the +1 in the DP formula). Another is failing to account for the fact that if , you can have as the left child and as the right, or vice versa (unless ). Also, many candidates forget to apply the modulo at each addition, leading to overflow issues.
When you see a problem where a solution for a number depends on solutions for its factors or smaller parts, think about sorting and DP. Sorting is a powerful preprocessing step that often reveals the order in which you should solve subproblems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Longest Square Streak in an Array | Medium | Solve | |
| Arithmetic Subarrays | Medium | Solve | |
| Maximize the Profit as the Salesman | Medium | Solve | |
| Maximum Earnings From Taxi | Medium | Solve | |
| Minimum Swaps to Sort by Digit Sum | Medium | Solve |