#3700

Number of ZigZag Arrays II

Hard
MathDynamic ProgrammingDynamic ProgrammingMatrix Exponentiation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Use dynamic programming to count valid transitions between states, leveraging matrix exponentiation for efficiency.

⚙️

Algorithm

3 steps
  1. 1Step 1: Define a state transition matrix based on ZigZag rules.
  2. 2Step 2: Use matrix exponentiation to compute the number of valid arrays of length n efficiently.
  3. 3Step 3: Sum the results from the last state to get the total count.
solution.py12 lines
1def countZigZagArrays(n, l, r):
2    mod = 10**9 + 7
3    m = r - l + 1
4    dp = [[0] * (2 * m) for _ in range(n)]
5    for i in range(m):
6        dp[0][i] = 1
7        dp[0][m + i] = 1
8    for i in range(1, n):
9        for j in range(m):
10            dp[i][j] = (sum(dp[i - 1][m + k] for k in range(m) if k != j) % mod)
11            dp[i][m + j] = (sum(dp[i - 1][k] for k in range(m) if k != j) % mod)
12    return sum(dp[n - 1]) % mod

Complexity note: The complexity is linear due to the dynamic programming approach, where we only store the last state.

  • 1ZigZag arrays require careful state management.
  • 2Dynamic programming can significantly reduce computation time.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.