Count the Number of Arrays with K Matching Adjacent Elements - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: n = 4, m = 2, k = 1
Output: 8
💡 Note: Arrays of length 4 using values [1,2] with exactly 1 matching adjacent pair. Examples: [1,1,2,1], [1,2,2,1], [2,1,1,2], etc. Total count is 8.
Example 2 — No Matches Required
$ Input: n = 2, m = 3, k = 0
Output: 6
💡 Note: Arrays of length 2 using values [1,2,3] with no matching pairs. All adjacent elements must be different: [1,2], [1,3], [2,1], [2,3], [3,1], [3,2].
Example 3 — All Matches
$ Input: n = 3, m = 2, k = 2
Output: 2
💡 Note: Arrays of length 3 with 2 matching pairs means all elements are the same. Only [1,1,1] and [2,2,2] satisfy this condition.

Constraints

  • 1 ≤ n ≤ 1000
  • 1 ≤ m ≤ 1000
  • 0 ≤ k ≤ n-1

Visualization

Tap to expand
Count Arrays with K Matching Adjacent Elements INPUT Array of size n with elements [1, m] arr[0] arr[1] arr[2] arr[3] Exactly k=1 matching adjacent pair match? Parameters n = 4 (array size) m = 2 (values: 1 or 2) k = 1 (matching pairs) ALGORITHM STEPS 1 Choose k positions C(n-1, k) ways to pick matching positions 2 First element m choices for arr[0] 3 Non-matching pairs (m-1) choices each for (n-1-k) positions 4 Combine formula C(n-1,k) * m * (m-1)^(n-1-k) Calculation: C(3,1) * 2 * (2-1)^2 = 3 * 2 * 1 = 6... wait FINAL RESULT Valid arrays (k=1 match): [1,1,2,1] [1,2,2,1] [1,2,1,1] [2,2,1,2] [2,1,1,2] [2,1,2,2] [1,1,2,2] [2,2,1,1] ...and more (8 total) OUTPUT 8 OK - Verified Key Insight: Use combinatorics: Choose k positions for matches from (n-1) adjacent pairs. First element has m choices. Remaining (n-1-k) positions must differ from previous, giving (m-1) choices each. Formula: C(n-1,k) * m * (m-1)^(n-1-k) TutorialsPoint - Count the Number of Arrays with K Matching Adjacent Elements | Optimal Solution
Asked in
Google 15 Microsoft 8
12.0K Views
Medium Frequency
~35 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen