Count the Number of Arrays with K Matching Adjacent Elements Problem
Description
LeetCode Problem 3405.
You are given three integers n, m, k. A good array arr of size n is defined as follows:
- Each element in
arris in the inclusive range[1, m]. - Exactly
kindicesi(where1 <= i < n) satisfy the conditionarr[i - 1] == arr[i].
Return the number of good arrays that can be formed.
Since the answer may be very large, return it modulo 10^9+ 7.
Example 1:
Input: n = 3, m = 2, k = 1
Output: 4
Explanation:
- There are 4 good arrays. They are [1, 1, 2], [1, 2, 2], [2, 1, 1] and [2, 2, 1].
- Hence, the answer is 4.
Example 2:
Input: n = 4, m = 2, k = 2
Output: 6
Explanation:
- The good arrays are [1, 1, 1, 2], [1, 1, 2, 2], [1, 2, 2, 2], [2, 1, 1, 1], [2, 2, 1, 1] and [2, 2, 2, 1].
- Hence, the answer is 6.
Example 3:
Input: n = 5, m = 2, k = 0
Output: 2
Explanation:
- The good arrays are [1, 2, 1, 2, 1] and [2, 1, 2, 1, 2]. Hence, the answer is 2.
Constraints:
1 <= n <= 10^51 <= m <= 10^50 <= k <= n - 1
Solution
Approach: Combinatorics + Fast Power
An array of length n has n - 1 adjacent pairs. We need exactly k of them to be equal and the other n - 1 - k to differ.
Choose which k pairs are equal: C(n - 1, k) ways. Those choices merge the array into n - k blocks of equal values. The first block can use any of m values, and each later block must differ from the block before it, giving m - 1 choices each. So the count is
C(n - 1, k) * m * (m - 1)^(n - k - 1) (mod 10^9 + 7)
Precompute factorials and inverse factorials once to get the binomial, and use fast exponentiation for the power.
Complexity: O(log n) per query after an O(N) precomputation.
mx = 10**5 + 10
mod = 10**9 + 7
f = [1] + [0] * mx
g = [1] + [0] * mx
for i in range(1, mx):
f[i] = f[i - 1] * i % mod
g[i] = pow(f[i], mod - 2, mod)
def comb(m: int, n: int) -> int:
return f[m] * g[n] * g[m - n] % mod
class Solution:
def countGoodArrays(self, n: int, m: int, k: int) -> int:
return comb(n - 1, k) * m * pow(m - 1, n - k - 1, mod) % mod