823. Binary Trees With Factors
Last updated
Last updated
/**
* Time complexity : O(N^2), where N is the length of arr.
* This comes from the two for-loops iterating i and j.
* Space complexity : O(N), the space used by map.
*/
class Solution {
public int numFactoredBinaryTrees(int[] arr) {
if(arr == null || arr.length == 0) {
return 0;
}
Arrays.sort(arr);
Map<Integer, Long> map = new HashMap<>();
for(int i = 0; i < arr.length; i++) {
long count = 1;
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 = 0;
for(long value: map.values()) {
totalCount += value;
}
return (int) (totalCount % 1000000007);
}
}