Count the Number of Arrays with K Matching Adjacent Elements - Problem
You're tasked with counting the number of good arrays of size n where each element is in the range [1, m] and exactly k adjacent pairs have matching values.
What makes an array "good"?
- The array has exactly
nelements - Each element
arr[i]is between1andm(inclusive) - There are exactly
kindices wherearr[i-1] == arr[i](matching adjacent elements)
Goal: Return the count of all possible good arrays, modulo 10^9 + 7.
Example: For n=3, m=2, k=1, arrays like [1,1,2] and [2,2,1] are good because they have exactly 1 matching adjacent pair.
Input & Output
example_1.py โ Basic Case
$
Input:
n = 3, m = 2, k = 1
โบ
Output:
6
๐ก Note:
With n=3 positions, m=2 colors, and k=1 match needed: Arrays like [1,1,2], [1,2,2], [2,1,1], [2,2,1], [1,2,1] with different arrangements give us 6 valid arrays total.
example_2.py โ No Matches
$
Input:
n = 2, m = 2, k = 0
โบ
Output:
2
๐ก Note:
Arrays must have no adjacent matches: [1,2] and [2,1] are the only valid arrays.
example_3.py โ All Matches
$
Input:
n = 3, m = 2, k = 2
โบ
Output:
2
๐ก Note:
Need exactly 2 adjacent matches (all elements same): [1,1,1] and [2,2,2] are the only valid arrays.
Constraints
- 1 โค n โค 1000
- 1 โค m โค 1000
- 0 โค k โค n-1
- Answer fits in 32-bit integer after taking modulo 109 + 7
Visualization
Tap to expand
Understanding the Visualization
1
Choose First Plank
Start with any of the m colors - this gives us m starting possibilities
2
Build Incrementally
At each step, decide: match previous color (if we haven't used all k matches) or pick a different color
3
Track State
Keep track of: current position, matches used so far, and whether we can continue a matching sequence
4
Use Memoization
Cache results for identical subproblems to avoid redundant calculations
Key Takeaway
๐ฏ Key Insight: Use DP to build arrays incrementally, making optimal choices at each step while tracking matches used
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code