Problem Description
You are given three integers n, m, and k. A good array arr of size n is such that:
- Each element in arr is in the inclusive range [1, m].
- Exactly k indices i (with 1 <= i < n) satisfy arr[i - 1] == arr[i].
Return the number of good arrays that can be formed modulo (10^9 + 7).
Key Insights
- The array can be viewed as being divided into segments; equal adjacent pairs occur inside a segment.
- If there are exactly k adjacent equal pairs in an array of n numbers, then the array forms (n - k) segments.
- The first element of the array can be chosen in m ways.
- Whenever a new segment begins, the number must change; hence there are (m - 1) choices for each new segment (after the first).
- The positions (in the n-1 gaps) where the segment breaks occur can be chosen in C(n-1, k) ways.
- The final formula becomes: result = m * (m - 1)^(n - 1 - k) * C(n - 1, k) mod (10^9+7).
Space and Time Complexity
Time Complexity: O(n) where n is up to 10^5 (main work is precomputing factorials and modular inverses). Space Complexity: O(n) for storing the factorials and inverse factorials arrays.
Solution
The core idea is to count the number of ways to partition the array into segments. With exactly k adjacent equal pairs, the array is split into (n - k) segments. The first element is free with m choices, and for each new segment (from the remaining (n-k-1) segments), we must choose a number different from the previous value, giving (m-1) choices each. In addition, we have to choose which k of the n-1 adjacent pairs are “equal” pairs (i.e. do not cause a new segment start). This is given by C(n-1, k). Multiplying these together gives:
result = m * (m - 1)^(n - 1 - k) * C(n-1, k) modulo (10^9+7).
This uses combinatorics, fast modular exponentiation, and factorial precomputation (with modular inverses) to compute the binomial coefficient C(n-1, k) efficiently.