Problem solution · Python

Find the Number of K-Even Arrays

Find the Number of K-Even Arrays: a Python solution using dynamic programming. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Dynamic programming
Source
walkccc LeetCode Solutions
Length
28 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Dynamic programming

For Find the Number of K-Even Arrays, the implementation records answers for smaller states and reuses them to build the requested result without repeating work.

  1. Define precisely what one DP state represents.
  2. Establish the base cases before transitions are evaluated.
  3. Process states in dependency order and combine only already-known values.

Code notes

  • 28 lines of Python from the credited upstream file 3339.py.
  • The implementation visibly relies on cached states.
  • No explicit loop blocks detected.

Complexity

Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeFind the Number of K-Even Arrays · PythonPython
Use this to learn the idea, then write your own version.
class Solution:  def countOfArrays(self, n: int, m: int, k: int) -> int:    MOD = 10**9 + 7    even = m // 2  # the number of even numbers in [1, m]    odd = m - even  # the number of odd numbers in [1, m]    # dp[i][j][0/1] := the number of arrays of length i with j consecutive even    # number pairs ending in an even number (0) or an odd number (1)    dp = [[[0] * 2          for _ in range(k + 1)]          for _ in range(n + 1)]     # Base case: arrays of length 1    # For an array of length 1, we can't have any even number pairs yet.    dp[1][0][0] = even    dp[1][0][1] = odd     for i in range(2, n + 1):      for j in range(k + 1):        # 1. Appending an even number to an array ending in an even number        #    creates a new consecutive even number pair.        # 2. Appending an even number to an array ending in an odd number.        dp[i][j][0] = ((dp[i - 1][j - 1][0] if j > 0 else 0) * even +                       dp[i - 1][j][1] * even) % MOD        # 3. Appending an odd number to an array.        dp[i][j][1] = sum(dp[i - 1][j]) * odd % MOD     return sum(dp[n][k]) % MOD 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗