Number of ZigZag Arrays II Problem
Description
LeetCode Problem 3700.
You are given three integers n, l, and r.
A ZigZag array of length n is defined as follows:
- Each element lies in the range
[l, r]. - No two adjacent elements are equal.
- No three consecutive elements form a strictly increasing or strictly decreasing sequence.
Return the total number of valid ZigZag arrays.
Since the answer may be large, return it modulo 10^9 + 7.
A sequence is said to be strictly increasing if each element is strictly greater than its previous one (if exists).
A sequence is said to be strictly decreasing if each element is strictly smaller than its previous one (if exists).
Example 1:
Input: n = 3, l = 4, r = 5
Output: 2
Explanation:
There are only 2 valid ZigZag arrays of length n = 3 using values in the range [4, 5]:
- [4, 5, 4]
- [5, 4, 5]
Example 2:
Input: n = 3, l = 1, r = 3
Output: 10
Explanation:
There are 10 valid ZigZag arrays of length n = 3 using values in the range [1, 3]:
- [1, 2, 1], [1, 3, 1], [1, 3, 2]
- [2, 1, 2], [2, 1, 3], [2, 3, 1], [2, 3, 2]
- [3, 1, 2], [3, 1, 3], [3, 2, 3]
All arrays meet the ZigZag conditions.
Constraints:
3 <= n <= 10^91 <= l < r <= 75
Solution
Approach: Matrix Exponentiation
Here n goes up to 10^9, so the length-by-length DP from the easy version is too slow, but the value range is tiny: m = r - l + 1 <= 75. A ZigZag array alternates between going up and going down, so a state is the last value plus the direction of the last step.
Let up[i] be the number of arrays ending at value i whose last step was an increase. Reflecting the values (i -> m - 1 - i) swaps increases and decreases, and the starting vector is all ones, so the number ending at i with a decrease is always up[m - 1 - i]. This halves the state to m numbers. One step is
up'[i] = sum of up[k] for k > m - 1 - i
which is a fixed m x m 0/1 matrix T. Starting from the all-ones vector (arrays of length 1), the vector after n - 1 steps is T^(n-1) times it, computed by repeated squaring. Each valid array ends with either an increase or a decrease, and by the symmetry the two groups have equal size, so the answer is 2 * sum(up) modulo 10^9 + 7.
Complexity: O(m^3 log n) time and O(m^2) space.
import operator
class Solution:
def zigZagArrays(self, n: int, l: int, r: int) -> int:
mod = 10**9 + 7
m = r - l + 1
def mul(a, bt):
return [[sum(map(operator.mul, row, col)) % mod for col in bt] for row in a]
# up[i] = arrays ending at i with an increase; by symmetry down[i] = up[m - 1 - i].
# One step: up'[i] = sum of up[k] for k > m - 1 - i.
trans = [[1 if k > m - 1 - i else 0 for k in range(m)] for i in range(m)]
vec = [1] * m
e = n - 1
while e:
if e & 1:
vec = [sum(map(operator.mul, row, vec)) % mod for row in trans]
e >>= 1
if e:
trans = mul(trans, list(zip(*trans)))
return 2 * sum(vec) % mod