-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathBinaryTreesWithFactors.java
More file actions
34 lines (26 loc) · 898 Bytes
/
BinaryTreesWithFactors.java
File metadata and controls
34 lines (26 loc) · 898 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
// TC : O(n2)
// SC: O(n)
public int numFactoredBinaryTrees(int[] arr) {
if(arr == null ||arr.length ==0){
return 0;
}
Arrays.sort(arr); // O(nlogn)
Map<Integer, Long> map = new HashMap<>();
for(int i=0;i< arr.length;i++){ // O(n2)
long count = 1l;
for(int j=0;j<i;j++){
if(arr[i] % arr[j] == 0 && map.containsKey(arr[i]/arr[j])){
count += map.get(arr[j]) * map.get(arr[i]/arr[j]);
}
}
map.put(arr[i], count);
}
long totalCount = 0l;
for(Map.Entry<Integer, Long> entry: map.entrySet()){
totalCount += entry.getValue();
System.out.println( " k " +entry.getKey() + " V "+ entry.getValue() );
}
return (int)(totalCount % (1000000000 + 7));
}
}