Skip to content

Commit 84dfacc

Browse files
authored
Create count-the-number-of-arrays-with-k-matching-adjacent-elements.py
1 parent 60a064e commit 84dfacc

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Time: O(n + logm)
2+
# Space: O(n)
3+
4+
# combinatorics, fast exponentiation
5+
MOD = 10**9+7
6+
FACT, INV, INV_FACT = [[1]*2 for _ in xrange(3)]
7+
def nCr(n, k):
8+
while len(INV) <= n: # lazy initialization
9+
FACT.append(FACT[-1]*len(INV) % MOD)
10+
INV.append(INV[MOD%len(INV)]*(MOD-MOD//len(INV)) % MOD) # https://cp-algorithms.com/algebra/module-inverse.html
11+
INV_FACT.append(INV_FACT[-1]*INV[-1] % MOD)
12+
return (FACT[n]*INV_FACT[n-k] % MOD) * INV_FACT[k] % MOD
13+
14+
15+
class Solution(object):
16+
def countGoodArrays(self, n, m, k):
17+
"""
18+
:type n: int
19+
:type m: int
20+
:type k: int
21+
:rtype: int
22+
"""
23+
return (nCr(n-1, k)*(m*pow(m-1, (n-1)-k, MOD)))%MOD

0 commit comments

Comments
 (0)