Skip to content

Commit

Permalink
Binary Trees With Factors
Browse files Browse the repository at this point in the history
  • Loading branch information
hikjik committed Oct 26, 2023
1 parent 1b9abb1 commit 31cf2f7
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 0 deletions.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ add_task(binary-tree-preorder-traversal)
add_task(binary-tree-right-side-view)
add_task(binary-tree-tilt)
add_task(binary-tree-zigzag-level-order-traversal)
add_task(binary-trees-with-factors)
add_task(binary-watch)
add_task(bitwise-and-of-numbers-range)
add_task(bitwise-xor-of-all-pairings)
Expand Down
1 change: 1 addition & 0 deletions solutions/binary-trees-with-factors/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
add_catch(test_binary_trees_with_factors test.cpp)
39 changes: 39 additions & 0 deletions solutions/binary-trees-with-factors/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#pragma once

#include <algorithm>
#include <cmath>
#include <numeric>
#include <vector>

class Solution {
public:
static constexpr int kMod = 1e9 + 7;

static int numFactoredBinaryTrees(std::vector<int> arr) {
std::sort(arr.begin(), arr.end());

std::unordered_map<int, int> indexes;
for (int i = 0; i < std::ssize(arr); ++i) {
indexes[arr[i]] = i;
}

std::vector<long long> dp(arr.size(), 1);
for (int i = 1; i < std::ssize(arr); ++i) {
for (int j = 0; j < i; ++j) {
if (arr[j] > std::sqrt(arr[i])) {
break;
}
if (arr[i] % arr[j] != 0) {
continue;
}
if (auto it = indexes.find(arr[i] / arr[j]); it != indexes.end()) {
const int k = it->second;
dp[i] += (k == j ? 1 : 2) * dp[j] * dp[k];
dp[i] %= kMod;
}
}
}

return std::accumulate(dp.begin(), dp.end(), 0LL) % kMod;
}
};
26 changes: 26 additions & 0 deletions solutions/binary-trees-with-factors/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#include <catch.hpp>

#include <solution.hpp>

TEST_CASE("Simple") {
struct TestCase {
std::vector<int> arr;
int expected;
};

std::vector<TestCase> test_cases{
{
.arr{2, 4, 5, 10},
.expected = 7,
},
{
.arr{2, 4},
.expected = 3,
},
};

for (const auto &[arr, expected] : test_cases) {
const auto actual = Solution::numFactoredBinaryTrees(arr);
REQUIRE(expected == actual);
}
}

0 comments on commit 31cf2f7

Please sign in to comment.