Skip to content

Commit

Permalink
Update Solution.java
Browse files Browse the repository at this point in the history
  • Loading branch information
godkingjay authored Oct 30, 2023
1 parent e2ec942 commit d05f60c
Showing 1 changed file with 26 additions and 48 deletions.
74 changes: 26 additions & 48 deletions Medium/823. Binary Trees With Factors/Solution.java
Original file line number Diff line number Diff line change
@@ -1,54 +1,32 @@
package hacktoberfest;
import java.util.*;

public class Solution {

// Method to count the number of binary trees that can be formed
public static int countBinaryTrees(int[] arr) {

// Method to count the number of binary trees that can be formed
public int numFactoredBinaryTrees(int[] arr) {
// Sort the array
Arrays.sort(arr);

// Create a map to store the count of subtrees for each element
Map<Integer, Long> subtreeCount = new HashMap<>();

for (int root : arr) {
subtreeCount.put(root, 1L);

for (int factor : arr) {
if (factor >= root) {
break;
}

/* Check if the current factor is a factor of the root
* and if the root/factor is present in the map */
if (root % factor == 0 && subtreeCount.containsKey(root / factor)) {
// Update the subtree count for the current root
subtreeCount.put(root,
(subtreeCount.get(root) + subtreeCount.get(factor) * subtreeCount.get(root / factor)));
}
}
}

long totalTrees = 0L;
for (int key : subtreeCount.keySet()) {
totalTrees = (totalTrees + subtreeCount.get(key)) % 1_000_000_007;
}

return (int) totalTrees;
}
Arrays.sort(arr);
// Create a map to store the count of subtrees for each element
Map<Integer, Long> subtreeCount = new HashMap<>();
for (int root : arr) {
subtreeCount.put(root, 1L);
for (int factor : arr) {
if (factor >= root) {
break;
}

// Driver Code
public static void main(String[] args) {
/* Check if the current factor is a factor of the root
* and if the root/factor is present in the map */
if (root % factor == 0 && subtreeCount.containsKey(root / factor)) {
// Update the subtree count for the current root
subtreeCount.put(root,
(subtreeCount.get(root) + subtreeCount.get(factor) * subtreeCount.get(root / factor)));
}
}
}

long totalTrees = 0L;
for (int key : subtreeCount.keySet()) {
totalTrees = (totalTrees + subtreeCount.get(key)) % 1_000_000_007;
}

int[] arr = {2, 4, 5, 10};

// Calculate the number of binary trees that can be formed
int ans = countBinaryTrees(arr);

// Print the result
System.out.println("Number of binary trees we can make = " + ans);

return (int) totalTrees;
}

}

0 comments on commit d05f60c

Please sign in to comment.