Problem summary: 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 109 + 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).
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming
Example 1
3
4
5
Example 2
3
1
3
Step 02
Core Insight
What unlocks the optimal approach
Use dynamic programming: let <code>dp[i][dir][x]</code> be the count of length-<code>i</code> sequences ending at value <code>x</code> where <code>dir</code> is the required next comparison (0 = down, 1 = up).
If the required move is <code>up</code> (dir=1) do <code>dp[i+1][0][y] += sum(dp[i][1][x]) for x < y</code>; if the required move is <code>down</code> (dir=0) do <code>dp[i+1][1][y] += sum(dp[i][0][x]) for x > y</code>.
Speed up with prefix/suffix sums so each layer updates in O(<code>m</code>) instead of O(<code>m</code><sup>2</sup>); take values mod <code>10<sup>9</sup>+7</code>.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3699: Number of ZigZag Arrays I
// Auto-generated Java example from go.
class Solution {
public void exampleSolution() {
}
}
// Reference (go):
// // Accepted solution for LeetCode #3699: Number of ZigZag Arrays I
// package main
//
// import "slices"
//
// // https://space.bilibili.com/206214
// func zigZagArrays1(n, l, r int) (ans int) {
// const mod = 1_000_000_007
// k := r - l + 1
// f0 := make([]int, k) // 后两个数递增
// f1 := make([]int, k) // 后两个数递减
// for i := range f0 {
// f0[i] = 1
// f1[i] = 1
// }
//
// s0 := make([]int, k+1)
// s1 := make([]int, k+1)
// for range n - 1 {
// for j, v := range f0 {
// s0[j+1] = s0[j] + v
// s1[j+1] = s1[j] + f1[j]
// }
// for j := range f0 {
// f0[j] = s1[j] % mod
// f1[j] = (s0[k] - s0[j+1]) % mod
// }
// }
//
// for j, v := range f0 {
// ans += v + f1[j]
// }
// return ans % mod
// }
//
// func zigZagArrays(n, l, r int) (ans int) {
// const mod = 1_000_000_007
// k := r - l + 1
// f := make([]int, k)
// for i := range f {
// f[i] = 1
// }
//
// for i := 1; i < n; i++ {
// pre := 0
// for j, v := range f {
// f[j] = pre % mod
// pre += v
// }
// slices.Reverse(f)
// }
//
// for _, v := range f {
// ans += v
// }
// return ans * 2 % mod
// }
// Accepted solution for LeetCode #3699: Number of ZigZag Arrays I
package main
import "slices"
// https://space.bilibili.com/206214
func zigZagArrays1(n, l, r int) (ans int) {
const mod = 1_000_000_007
k := r - l + 1
f0 := make([]int, k) // 后两个数递增
f1 := make([]int, k) // 后两个数递减
for i := range f0 {
f0[i] = 1
f1[i] = 1
}
s0 := make([]int, k+1)
s1 := make([]int, k+1)
for range n - 1 {
for j, v := range f0 {
s0[j+1] = s0[j] + v
s1[j+1] = s1[j] + f1[j]
}
for j := range f0 {
f0[j] = s1[j] % mod
f1[j] = (s0[k] - s0[j+1]) % mod
}
}
for j, v := range f0 {
ans += v + f1[j]
}
return ans % mod
}
func zigZagArrays(n, l, r int) (ans int) {
const mod = 1_000_000_007
k := r - l + 1
f := make([]int, k)
for i := range f {
f[i] = 1
}
for i := 1; i < n; i++ {
pre := 0
for j, v := range f {
f[j] = pre % mod
pre += v
}
slices.Reverse(f)
}
for _, v := range f {
ans += v
}
return ans * 2 % mod
}
# Accepted solution for LeetCode #3699: Number of ZigZag Arrays I
# Time: O(n * (r - l))
# Space: O(r - l)
# prefix sum, dp
class Solution(object):
def zigZagArrays(self, n, l, r):
"""
:type n: int
:type l: int
:type r: int
:rtype: int
"""
MOD = 10**9+7
r -= l
dp = [1]*(r+1)
for _ in xrange(n-1):
prefix = 0
for i in xrange(len(dp)):
dp[i], prefix = prefix, (prefix+dp[i])%MOD
dp.reverse()
return (reduce(lambda accu, x: (accu+x)%MOD, dp, 0)*2)%MOD
// Accepted solution for LeetCode #3699: Number of ZigZag Arrays I
// Rust example auto-generated from go reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (go):
// // Accepted solution for LeetCode #3699: Number of ZigZag Arrays I
// package main
//
// import "slices"
//
// // https://space.bilibili.com/206214
// func zigZagArrays1(n, l, r int) (ans int) {
// const mod = 1_000_000_007
// k := r - l + 1
// f0 := make([]int, k) // 后两个数递增
// f1 := make([]int, k) // 后两个数递减
// for i := range f0 {
// f0[i] = 1
// f1[i] = 1
// }
//
// s0 := make([]int, k+1)
// s1 := make([]int, k+1)
// for range n - 1 {
// for j, v := range f0 {
// s0[j+1] = s0[j] + v
// s1[j+1] = s1[j] + f1[j]
// }
// for j := range f0 {
// f0[j] = s1[j] % mod
// f1[j] = (s0[k] - s0[j+1]) % mod
// }
// }
//
// for j, v := range f0 {
// ans += v + f1[j]
// }
// return ans % mod
// }
//
// func zigZagArrays(n, l, r int) (ans int) {
// const mod = 1_000_000_007
// k := r - l + 1
// f := make([]int, k)
// for i := range f {
// f[i] = 1
// }
//
// for i := 1; i < n; i++ {
// pre := 0
// for j, v := range f {
// f[j] = pre % mod
// pre += v
// }
// slices.Reverse(f)
// }
//
// for _, v := range f {
// ans += v
// }
// return ans * 2 % mod
// }
// Accepted solution for LeetCode #3699: Number of ZigZag Arrays I
// Auto-generated TypeScript example from go.
function exampleSolution(): void {
}
// Reference (go):
// // Accepted solution for LeetCode #3699: Number of ZigZag Arrays I
// package main
//
// import "slices"
//
// // https://space.bilibili.com/206214
// func zigZagArrays1(n, l, r int) (ans int) {
// const mod = 1_000_000_007
// k := r - l + 1
// f0 := make([]int, k) // 后两个数递增
// f1 := make([]int, k) // 后两个数递减
// for i := range f0 {
// f0[i] = 1
// f1[i] = 1
// }
//
// s0 := make([]int, k+1)
// s1 := make([]int, k+1)
// for range n - 1 {
// for j, v := range f0 {
// s0[j+1] = s0[j] + v
// s1[j+1] = s1[j] + f1[j]
// }
// for j := range f0 {
// f0[j] = s1[j] % mod
// f1[j] = (s0[k] - s0[j+1]) % mod
// }
// }
//
// for j, v := range f0 {
// ans += v + f1[j]
// }
// return ans % mod
// }
//
// func zigZagArrays(n, l, r int) (ans int) {
// const mod = 1_000_000_007
// k := r - l + 1
// f := make([]int, k)
// for i := range f {
// f[i] = 1
// }
//
// for i := 1; i < n; i++ {
// pre := 0
// for j, v := range f {
// f[j] = pre % mod
// pre += v
// }
// slices.Reverse(f)
// }
//
// for _, v := range f {
// ans += v
// }
// return ans * 2 % mod
// }
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n × m)
Space
O(n × m)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.