Skip to main content

Number of ZigZag Arrays II - Solution & Explanation

HardMathDynamic Programming4 min readAsked at: Amazon, Google, Bloomberg
Practice this 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 <= 109
  • 1 <= l < r <= 75​​​​​​​

Approach Overview

Problem Overview: You need to count how many arrays satisfy a zigzag pattern, where adjacent elements strictly alternate between increasing and decreasing. The task is combinatorial in nature, and brute-force generation quickly becomes infeasible as the array length grows.

Approach 1: Brute Force Enumeration (Exponential Time, O(n) Space)

The most direct idea is to generate every possible array and check whether it satisfies the zigzag condition. During generation, compare each adjacent pair and ensure the relationship alternates between < and >. This approach uses recursion or backtracking and keeps track of the previous value and the expected direction. While simple to reason about, the search space grows exponentially with the array length, leading to O(m^n) time complexity and O(n) recursion stack space.

Approach 2: Dynamic Programming with Direction State (O(n * m^2) Time, O(n * m) Space)

A better approach models the problem using dynamic programming. Let dp[i][v][d] represent the number of valid zigzag arrays of length i that end with value v, where d indicates whether the previous step was increasing or decreasing. To transition, iterate through all valid previous values that satisfy the required relation (smaller values for an increasing step, larger values for a decreasing step). This captures the alternating constraint explicitly, but each transition may scan many candidate values, producing O(n * m^2) time.

Approach 3: DP with Prefix Sum Optimization (O(n * m) Time, O(n * m) Space)

The optimized solution removes the inner scan using prefix sums. Instead of iterating over all smaller or larger values, maintain cumulative counts so each transition becomes a constant-time lookup. For example, when computing increasing states, you sum all counts from values smaller than the current value using a prefix array. For decreasing states, use a suffix or reversed prefix sum. This transforms the DP transition into O(1), reducing the total complexity to O(n * m) time and O(n * m) space. The approach combines ideas from math counting techniques and efficient DP transitions.

Recommended for interviews: Start by explaining the brute-force generation to show you understand the zigzag constraint. Then transition to the DP formulation that tracks the last value and direction. Interviewers typically expect the prefix-sum optimized DP because it demonstrates strong command of dynamic programming state design and transition optimization.

Solution

Code

Java

Try this approach in the editor β†’

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force BacktrackingO(m^n)O(n)Useful for understanding the zigzag constraint or verifying small inputs
Dynamic Programming (State: index, value, direction)O(n * m^2)O(n * m)Good intermediate solution when constraints are moderate
DP with Prefix Sum OptimizationO(n * m)O(n * m)Optimal approach for large inputs; eliminates expensive inner loops

Video Solution

Number of ZigZag Arrays II | Leetcode - 3700 β€’ Shivam Gupta β€’ 2,138 views views

Watch 9 more video solutions β†’

Frequently Asked Questions

Is Number of ZigZag Arrays II easy or hard?
Number of ZigZag Arrays II is categorized as Hard because it requires careful DP state design and optimization. A naive DP leads to O(n * m^2) transitions, and recognizing the prefix sum optimization is the key step to reach the optimal solution.
Number of ZigZag Arrays II Python/Java solution
Implement a DP table where dp[i][v][dir] stores the number of valid arrays of length i ending at value v with direction dir. Maintain prefix sums to compute transitions efficiently. The same logic works in Python, Java, C++, and Go with O(n * m) complexity.
How to solve Number of ZigZag Arrays II in O(n*m)?
Define DP states that track the array length, last value, and the direction of the previous comparison (up or down). Maintain prefix sums of counts for each direction so transitions from smaller or larger values can be computed instantly. This eliminates the inner loop and reduces the complexity to O(n * m).
What is the best approach for Number of ZigZag Arrays II?
The most efficient approach uses dynamic programming with prefix sum optimization. The DP tracks the last value and whether the previous step was increasing or decreasing. Prefix sums allow transitions from smaller or larger values in constant time, giving O(n * m) time complexity and O(n * m) space.
Is Number of ZigZag Arrays II asked at Google/Amazon/Meta?
Zigzag and alternating sequence problems frequently appear in interviews at companies like Google, Amazon, and Meta because they test dynamic programming state design and combinatorial reasoning. Variants of alternating array counting and wiggle sequence problems are common interview topics.
What data structure is used in Number of ZigZag Arrays II?
The main structure is a dynamic programming table that stores counts for each length, ending value, and direction state. Prefix sum arrays are used to accelerate transitions by quickly aggregating counts of smaller or larger values.
What is the time complexity of Number of ZigZag Arrays II?
The optimized dynamic programming solution runs in O(n * m) time, where n is the array length and m is the range of possible values. Each DP state is computed using prefix sums instead of scanning all candidates, reducing the transition cost to O(1). Space complexity is O(n * m).

Ready to solve this problem?

Practice Number of ZigZag Arrays II with our built-in code editor and test cases.

Practice on FleetCode