Skip to content

Commit fd35326

Browse files
committed
"Binary Trees With Factors" solution
1 parent cf8f179 commit fd35326

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

src/binary_trees_with_factors.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from collections import defaultdict
2+
3+
4+
MOD = 10**9 + 7
5+
6+
7+
class Solution:
8+
def numFactoredBinaryTrees(self, arr: list[int]) -> int:
9+
cache: dict[int, int] = defaultdict(int)
10+
sorted_arr = sorted(arr)
11+
12+
for i, x in enumerate(sorted_arr):
13+
options = 1
14+
15+
for j in range(i):
16+
if x % sorted_arr[j] == 0:
17+
a = x // sorted_arr[j]
18+
b = x // a
19+
20+
options += cache[a] * cache[b]
21+
22+
cache[x] = options
23+
24+
return sum(cache.values()) % MOD
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import pytest
2+
3+
from src.binary_trees_with_factors import Solution
4+
5+
6+
@pytest.mark.parametrize(
7+
"arr,expected",
8+
(
9+
([2, 4], 3),
10+
([2, 4, 5, 10], 7),
11+
([15, 13, 22, 7, 11], 5),
12+
),
13+
)
14+
def test_solution(arr, expected):
15+
assert Solution().numFactoredBinaryTrees(arr) == expected

0 commit comments

Comments
 (0)