#3405
Count the Number of Arrays with K Matching Adjacent Elements
HardMathCombinatoricsCombinatoricsDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Use combinatorial counting to determine valid configurations without generating all arrays. This leverages the structure of the problem.
⚙️
Algorithm
3 steps- 1Step 1: Choose the first element (m options).
- 2Step 2: Choose k positions to have matching adjacent elements.
- 3Step 3: Fill the remaining positions with different elements (m-1 options).
solution.py5 lines
1def count_good_arrays(n, m, k):
2 MOD = 10**9 + 7
3 if k > n - 1:
4 return 0
5 return (m * pow(m - 1, n - k - 1, MOD)) % MODℹ
Complexity note: The optimal solution runs in O(n) due to the power calculation, making it efficient for large inputs.
- 1Choosing the first element defines the rest of the array structure.
- 2The number of ways to choose positions for matches is combinatorial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.