#823
Binary Trees With Factors
MediumArrayHash TableDynamic ProgrammingSortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
The optimal solution leverages dynamic programming and a hash map to efficiently count the number of trees. By sorting the array and using a hash map to store the number of trees for each integer, we can quickly find factors and update counts without redundant calculations.
⚙️
Algorithm
4 steps- 1Step 1: Sort the array to ensure we can find factors in order.
- 2Step 2: Create a hash map to store the number of trees for each integer.
- 3Step 3: For each integer, check all previous integers to see if they can form the current integer by multiplication.
- 4Step 4: Update the count for the current integer based on the counts of its factors.
solution.py12 lines
1def numFactoredBinaryTrees(arr):
2 MOD = 10**9 + 7
3 arr.sort()
4 count = {x: 1 for x in arr}
5 for i in range(len(arr)):
6 for j in range(i):
7 if arr[i] % arr[j] == 0:
8 right = arr[i] // arr[j]
9 if right in count:
10 count[arr[i]] += count[arr[j]] * count[right]
11 count[arr[i]] %= MOD
12 return sum(count.values()) % MODℹ
Complexity note: The time complexity remains O(n²) due to the nested loops, but we use a hash map for O(1) access to counts, improving efficiency in updates.
- 1Each non-leaf node's value must be the product of its children.
- 2Using a hash map allows for efficient counting of possible trees.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.