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: n=4, m=2, k=11 or 21 or 21 or 21 or 2Need exactly 1 matching adjacent pairValid Examples:[1,1,2,1] - match at positions 0,1[1,2,2,1] - match at positions 1,2[2,1,1,2] - match at positions 1,2... (5 more valid arrays)Formula: C(3,1) × 2 × (2-1)² = 3 × 2 × 4 = 24... wait, let me recalculateActually: C(3,1) × 2 × (2-1)²⁻¹ = 3 × 2 × 2¹ = 12... hmmCorrect answer: 8 arrays total
Understanding the Visualization
1
Input
Array length n=4, values 1 to m=2, need k=1 matches
2
Process
Choose positions for matches, then fill systematically
3
Output
Count of valid arrays = 8
Key Takeaway
🎯 Key Insight: Use combinatorics to choose match positions, then fill systematically
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