|
| 1 | +/* |
| 2 | +Problem Link: https://leetcode.com/problems/binary-trees-with-factors/description/ |
| 3 | +
|
| 4 | +Problem Statement: |
| 5 | +Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1. |
| 6 | +
|
| 7 | +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. |
| 8 | +
|
| 9 | +Return the number of binary trees we can make. The answer may be too large so return the answer modulo 109 + 7. |
| 10 | +Solution Approach: |
| 11 | +/**sort the array so as to start with the smallest element, as larger elements can be formed with the help of smaller one |
| 12 | + * and use HashMap to record each Integer, and the number of trees with that Integer as root |
| 13 | + * (1) each integer A[i] will always have one tree with only itself |
| 14 | + * (2) if A[i] has divisor (a) in the map, and if A[i]/a also in the map |
| 15 | + * then a can be the root of its left subtree, and A[i]/a can be the root of its right subtree; |
| 16 | + * the number of such tree is map.get(a) * map.get(A[i]/a) [calculating all possible combinations] |
| 17 | + * (3) sum over the map will give us all possible trees |
| 18 | + */ |
| 19 | + |
| 20 | +*/ |
| 21 | + |
| 22 | +/* ------------CODE---------------- */ |
| 23 | + |
| 24 | +class Solution { |
| 25 | + public int numFactoredBinaryTrees(int[] arr) { |
| 26 | + long mod = 1000000007; |
| 27 | + Arrays.sort(arr); |
| 28 | + Map<Integer, Long> hmap = new HashMap<>(); |
| 29 | + long count = 1; |
| 30 | + hmap.put(arr[0], count); |
| 31 | + |
| 32 | + for(int i=1; i<arr.length; i++) { |
| 33 | + // intializing count for each node |
| 34 | + count = 1; |
| 35 | + int curr = arr[i]; |
| 36 | + for(Integer n : hmap.keySet()) { |
| 37 | + if(curr%n==0 && hmap.containsKey(curr/n)) { |
| 38 | + count += (hmap.get(curr/n) * hmap.get(n))%mod; |
| 39 | + } |
| 40 | + } |
| 41 | + hmap.put(curr, count); |
| 42 | + } |
| 43 | + |
| 44 | + long ans = 0; |
| 45 | + for(Integer temp: hmap.keySet()) { |
| 46 | + ans = (ans + hmap.get(temp))%mod; |
| 47 | + } |
| 48 | + |
| 49 | + return (int)ans; |
| 50 | + } |
| 51 | +} |
| 52 | +/* |
| 53 | +Time Complexity: O(n^2) - all about traversing number of elements in the hashmap |
| 54 | +Space Complexity: |
| 55 | +*/ |
0 commit comments