Count the Number of Arrays with K Matching Adjacent Elements

You are given three integers n, m, and k. A good array arr of size n is defined as follows:

  • Each element in arr is in the inclusive range [1, m].
  • Exactly k indices i, where 1 <= i < n, satisfy the condition arr[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
Inputn = 3, m = 2, k = 1
Output4
There are 4 good arrays: [1, 1, 2], [1, 2, 2], [2, 1, 1], and [2, 2, 1].
Example 2
Inputn = 4, m = 2, k = 2
Output6
There are 6 good arrays: [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].

Constraints

  • 1 <= n <= 10^5
  • 1 <= m <= 10^5
  • 0 <= k <= n - 1

Asked at 5 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate