Skip to content

Commit 60a064e

Browse files
authored
Create count-the-number-of-arrays-with-k-matching-adjacent-elements.cpp
1 parent 25fcdef commit 60a064e

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Time: O(n + logm)
2+
// Space: O(n)
3+
4+
// combinatorics, fast exponentiation
5+
static const int MOD = 1e9 + 7;
6+
vector<int64_t> FACT = {1, 1};
7+
vector<int64_t> INV = {1, 1};
8+
vector<int64_t> INV_FACT = {1, 1};
9+
int nCr(int n, int k) {
10+
while (size(INV) <= n) { // lazy initialization
11+
FACT.emplace_back((FACT.back() *size(INV)) % MOD);
12+
INV.emplace_back(((INV[MOD % size(INV)]) * (MOD - MOD / size(INV))) % MOD); // https://cp-algorithms.com/algebra/module-inverse.html
13+
INV_FACT.emplace_back((INV_FACT.back() * INV.back()) % MOD);
14+
}
15+
return (((FACT[n] * INV_FACT[n - k]) % MOD) * INV_FACT[k]) % MOD;
16+
}
17+
18+
class Solution {
19+
public:
20+
int countGoodArrays(int n, int m, int k) {
21+
const auto& powmod = [&](int a, int b) {
22+
a %= MOD;
23+
int64_t result = 1;
24+
while (b) {
25+
if (b & 1) {
26+
result = result * a % MOD;
27+
}
28+
a = int64_t(a) * a % MOD;
29+
b >>= 1;
30+
}
31+
return result;
32+
};
33+
34+
return (nCr(n - 1, k) * (m * powmod(m - 1, (n - 1) - k) % MOD)) % MOD;
35+
}
36+
};

0 commit comments

Comments
 (0)