LeetCode #3699 — HARD

Number of ZigZag Arrays I

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

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).

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 <= 2000
  • 1 <= l < r <= 2000
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

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

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. 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
// }
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.