Find the Number of K-Even Arrays - Problem

You're tasked with counting special arrays based on a unique mathematical property! Given three integers n (array size), m (maximum value), and k (target count), you need to find how many arrays of size n have exactly k "magic pairs".

A magic pair occurs at index i when the expression (arr[i] * arr[i+1]) - arr[i] - arr[i+1] evaluates to an even number. All array elements must be in the range [1, m].

Goal: Count all possible k-even arrays and return the result modulo 10^9 + 7.

Example: For array [2, 3, 1], check pairs: (2*3) - 2 - 3 = 1 (odd), (3*1) - 3 - 1 = -1 (odd). This array has 0 magic pairs.

Input & Output

example_1.py โ€” Basic Case
$ Input: n = 3, m = 2, k = 1
โ€บ Output: 4
๐Ÿ’ก Note: Arrays with exactly 1 magic pair: [1,1,2], [2,2,1], [1,2,2], [2,1,1]. Magic pairs occur when both numbers have same parity (both odd or both even).
example_2.py โ€” No Magic Pairs
$ Input: n = 2, m = 3, k = 0
โ€บ Output: 6
๐Ÿ’ก Note: Arrays with 0 magic pairs: [1,2], [1,3], [2,1], [2,3], [3,1], [3,2]. All pairs have different parity (one odd, one even).
example_3.py โ€” Edge Case
$ Input: n = 1, m = 5, k = 0
โ€บ Output: 5
๐Ÿ’ก Note: Single element arrays have no adjacent pairs, so k must be 0. All 5 possible arrays [1], [2], [3], [4], [5] are valid.

Constraints

  • 1 โ‰ค n โ‰ค 1000
  • 1 โ‰ค m โ‰ค 1000
  • 0 โ‰ค k โ‰ค n-1
  • Answer must be returned modulo 109 + 7

Visualization

Tap to expand
Dynamic Programming: Building K-Even ArraysPosition 0Odd: (m+1)/2 waysEven: m/2 waysPosition 1Check parity matchUpdate magic countPosition 2Continue buildingTrack all statesState Transition Formuladp[pos][parity][count] += dp[pos-1][prev_parity][prev_count]if (parity == prev_parity): new_count = prev_count + 1else: new_count = prev_countFinal Answer: Sum of dp[n-1][any_parity][k]
Understanding the Visualization
1
State Definition
dp[position][last_parity][magic_count] = number of ways
2
Transition Logic
For each new number, check if it creates a magic pair with previous
3
Parity Check
Magic pair formed when both numbers odd or both even
4
Final Count
Sum all states with exactly k magic pairs
Key Takeaway
๐ŸŽฏ Key Insight: Use DP to track position, last element's parity, and magic pair count. Magic pairs form when adjacent elements have same parity, making this a manageable state space of O(n*2*k).
Asked in
Google 25 Meta 18 Amazon 15 Microsoft 12
28.4K Views
Medium Frequency
~25 min Avg. Time
890 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