Skip to content

Commit 50c499b

Browse files
authored
Merge pull request #2 from divi-259/lc
Leetcode Questions Update
2 parents e9f90b2 + 0fcd658 commit 50c499b

16 files changed

+188
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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+
*/
File renamed without changes.
File renamed without changes.

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy