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
arris in the inclusive range[1, m] - Exactly k indices
i(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.
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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code