Skip to main content

Number of ZigZag Arrays III - Solution & Explanation

HardPremiumFree on FleetCode4 min read
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.

 

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 <= 200
  • 1 <= l < r <= 10​​​​​​​9

Approach Overview

Problem Overview: You are given constraints for building arrays that follow a zigzag pattern, meaning adjacent elements must alternate between increasing and decreasing. The task is to count how many valid arrays satisfy this alternating pattern while respecting the value bounds.

Approach 1: Brute Force Enumeration (Exponential Time, O(m^n) time, O(n) space)

The most direct idea is to generate every possible array of length n with values in the allowed range and check whether it forms a valid zigzag pattern. During generation, you track the previous element and verify that the direction alternates between < and >. This uses recursive backtracking to build arrays element by element. While simple to reason about, the search space grows exponentially with m^n, making it infeasible except for tiny inputs.

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

A better strategy stores partial results. Define dp[i][v][d] as the number of zigzag arrays of length i ending with value v, where d indicates whether the last comparison was increasing or decreasing. For each new position, iterate over all previous values that satisfy the alternating condition. If the previous step was increasing, the next value must be smaller; if decreasing, the next must be larger. This reduces the problem to structured transitions between states, which is a common pattern in dynamic programming. The main cost comes from scanning all possible previous values for each transition.

Approach 3: DP with Prefix Sum Optimization (O(n*m) time, O(n*m) space)

The quadratic transition in the previous method can be optimized. Instead of iterating through all valid previous values each time, maintain prefix sums of DP counts. When you need the number of ways where the previous value is smaller or larger than the current value, compute it in constant time using cumulative sums. This converts the expensive nested loops into simple prefix lookups. The technique is similar to range-sum transitions used in prefix sum optimization for DP. The result is an O(n*m) algorithm that scales to large constraints.

Approach 4: Combinatorial DP Compression (O(n*m) time, O(m) space)

Space can be reduced by observing that each row of the DP depends only on the previous row. Keep two arrays representing counts for increasing and decreasing endings, then update them using prefix sums. This rolling-array technique is common in memory-optimized dynamic programming. The time complexity remains linear in the state space while reducing memory usage significantly.

Recommended for interviews: Start by describing the brute-force generation to show understanding of the zigzag constraint. Then move quickly to the dynamic programming formulation with direction states. The optimized DP using prefix sums is the solution interviewers typically expect because it reduces the transition from O(m) to O(1), bringing total complexity down to O(n*m).

Solutions for this problem are being prepared.

Try solving it yourself

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force EnumerationO(m^n)O(n)Conceptual baseline or very small constraints
Dynamic Programming with Direction StateO(n*m^2)O(n*m)When constraints are moderate and transitions are easy to reason about
DP with Prefix Sum OptimizationO(n*m)O(n*m)General optimal approach for large inputs
Space-Optimized Rolling DPO(n*m)O(m)When memory usage matters or constraints are very large

Frequently Asked Questions

Is Number of ZigZag Arrays III easy or hard?
Number of ZigZag Arrays III is considered a hard problem because it requires modeling alternating relationships and optimizing DP transitions. Recognizing that prefix sums can eliminate the inner loop is the key insight that reduces complexity from O(n*m^2) to O(n*m).
Number of ZigZag Arrays III Python/Java solution
Implement a DP table where dp[i][v][d] represents the number of ways to build length i ending with value v and direction d (up or down). Maintain prefix sums of the previous row to compute counts of smaller or larger values quickly. This approach works efficiently in Python, Java, and C++ with O(n*m) time.
How to solve Number of ZigZag Arrays III in O(n)?
The problem typically cannot be solved in pure O(n) because the DP state depends on both the position and the value range. The practical optimal complexity is O(n*m), achieved by combining dynamic programming with prefix sum range queries to compute transitions efficiently.
What is the best approach for Number of ZigZag Arrays III?
The most efficient approach uses dynamic programming with prefix sum optimization. Track the number of arrays ending at each value with the last relation being increasing or decreasing. Prefix sums allow you to compute valid transitions in constant time, reducing the complexity to O(n*m) with O(n*m) or O(m) space.
Is Number of ZigZag Arrays III asked at Google/Amazon/Meta?
Zigzag pattern counting and alternating sequence problems appear frequently in interviews at large tech companies. Variants using dynamic programming and prefix sums have been reported in interviews at companies like Google, Amazon, and Meta, especially for algorithm-focused roles.
What data structure is used in Number of ZigZag Arrays III?
The core structure is a dynamic programming table that tracks counts of valid sequences by index, last value, and comparison direction. Prefix sum arrays are added to accelerate range queries during state transitions.
What is the time complexity of Number of ZigZag Arrays III?
The optimal solution runs in O(n*m) time using dynamic programming with prefix sums, where n is the array length and m is the range of possible values. A simpler DP approach without prefix sums costs O(n*m^2), while brute-force enumeration grows exponentially as O(m^n).

Ready to solve this problem?

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

Practice on FleetCode