Skip to content

Commit 97f9eb1

Browse files
authored
solution(java): 823. Binary Trees With Factors
823. Binary Trees With Factors - Java
2 parents 970f4ae + d05f60c commit 97f9eb1

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<h3>823. Binary Trees With Factors</h3><br>
2+
<strong>Medium</strong><br><br>
3+
4+
Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1.
5+
6+
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.
7+
8+
Return the number of binary trees we can make. The answer may be too large so return the answer modulo 109 + 7.
9+
<br>
10+
11+
Example 1:<br>
12+
Input: arr = [2,4]<br>
13+
Output: 3<br>
14+
Explanation: We can make these trees: [2], [4], [4, 2, 2]
15+
<br>
16+
17+
Example 2:<br>
18+
Input: arr = [2,4,5,10<br>
19+
Output: 7<br>
20+
Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].
21+
<br>
22+
23+
Constraints:<br>
24+
1. <= arr.length <= 1000<br>
25+
2. <= arr[i] <= 109<br>
26+
All the values of arr are unique.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
public class Solution {
2+
// Method to count the number of binary trees that can be formed
3+
public int numFactoredBinaryTrees(int[] arr) {
4+
// Sort the array
5+
Arrays.sort(arr);
6+
// Create a map to store the count of subtrees for each element
7+
Map<Integer, Long> subtreeCount = new HashMap<>();
8+
for (int root : arr) {
9+
subtreeCount.put(root, 1L);
10+
for (int factor : arr) {
11+
if (factor >= root) {
12+
break;
13+
}
14+
15+
/* Check if the current factor is a factor of the root
16+
* and if the root/factor is present in the map */
17+
if (root % factor == 0 && subtreeCount.containsKey(root / factor)) {
18+
// Update the subtree count for the current root
19+
subtreeCount.put(root,
20+
(subtreeCount.get(root) + subtreeCount.get(factor) * subtreeCount.get(root / factor)));
21+
}
22+
}
23+
}
24+
25+
long totalTrees = 0L;
26+
for (int key : subtreeCount.keySet()) {
27+
totalTrees = (totalTrees + subtreeCount.get(key)) % 1_000_000_007;
28+
}
29+
30+
return (int) totalTrees;
31+
}
32+
}

0 commit comments

Comments
 (0)