Find the Number of K-Even Arrays - Problem

You are given three integers n, m, and k. An array arr is called k-even if there are exactly k indices such that, for each of these indices i (0 ≤ i < n - 1):

(arr[i] * arr[i + 1]) - arr[i] - arr[i + 1] is even.

Return the number of possible k-even arrays of size n where all elements are in the range [1, m]. Since the answer may be very large, return it modulo 109 + 7.

Input & Output

Example 1 — Basic Case
$ Input: n = 3, m = 2, k = 1
Output: 4
💡 Note: Arrays with exactly 1 even pair: [1,1,2], [2,1,1], [1,2,2], [2,2,1]. Each has one adjacent pair with same parity making (a*b-a-b) even.
Example 2 — No Even Pairs
$ Input: n = 2, m = 2, k = 0
Output: 2
💡 Note: Arrays with 0 even pairs: [1,2], [2,1]. Different parities make (1*2-1-2)=-1 odd, (2*1-2-1)=-1 odd.
Example 3 — All Even Pairs
$ Input: n = 2, m = 2, k = 1
Output: 1
💡 Note: Arrays with exactly 1 even pair: [2,2]. Only when both adjacent numbers are even does (a*b-a-b) become even: (2*2-2-2)=0.

Constraints

  • 1 ≤ n ≤ 1000
  • 1 ≤ m ≤ 1000
  • 0 ≤ k ≤ n-1

Visualization

Tap to expand
K-Even Arrays Problem INPUT n = 3, m = 2, k = 1 Array of size n=3: a[0] a[1] a[2] i=0 i=1 i=2 Elements in range [1, m] Values: 1 or 2 K-Even Condition: (a[i]*a[i+1])-a[i]-a[i+1] must be even for k=1 pairs Check n-1 = 2 adjacent pairs Need exactly k=1 even result ALGORITHM STEPS 1 Simplify Condition (a*b)-a-b = (a-1)(b-1)-1 Even when both odd 2 Count Odd/Even in [1,m] odd = m/2 (rounded up) = 1 even = m/2 = 1 3 DP State Definition dp[i][j] = ways to fill i elements with j even pairs 4 Transition If prev odd, next odd: j+1 Otherwise: j unchanged DP Transitions Odd--Odd: even pair Odd--Even: odd pair Even--Odd: odd pair Even--Even: odd pair FINAL RESULT Valid K-Even Arrays (k=1): 1 1 2 [1,1,2] 2 1 1 [2,1,1] 1 2 1 [1,2,1] 2 1 2 [2,1,2] Output: 4 mod (10^9 + 7) Verification: Each array has exactly 1 adjacent odd-odd pair Status: OK Key Insight: The expression (a*b)-a-b simplifies to (a-1)(b-1)-1. This is even only when both (a-1) and (b-1) are odd, which means both a and b must be odd. Use DP to track the count of odd-odd adjacent pairs while building the array. Time Complexity: O(n*k), Space Complexity: O(n*k) or O(k) with optimization. TutorialsPoint - Find the Number of K-Even Arrays | Optimal Solution (Dynamic Programming)
Asked in
Google 15 Microsoft 12 Amazon 8
28.0K Views
Medium Frequency
~35 min Avg. Time
845 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