#3699

Number of ZigZag Arrays I

Hard
Dynamic ProgrammingPrefix SumDynamic ProgrammingPrefix Sum
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * (r - l)^2)
Space
O(1)
O(n * (r - l))
💡

Intuition

Time O(n * (r - l)^2)Space O(n * (r - l))

Use dynamic programming to count valid sequences based on the last element and direction of the last move, leveraging prefix sums for efficiency.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP table where dp[i][dir][x] counts sequences of length i ending at x with direction dir.
  2. 2Step 2: Fill the DP table using the rules for ZigZag arrays based on the last direction and valid transitions.
  3. 3Step 3: Sum the counts from the last row of the DP table to get the total valid ZigZag arrays.
solution.py13 lines
1def zigzagArrays(n, l, r):
2    mod = 10**9 + 7
3    dp = [[[0] * (r + 1) for _ in range(2)] for _ in range(n + 1)]
4    for x in range(l, r + 1):
5        dp[1][0][x] = dp[1][1][x] = 1
6    for i in range(1, n):
7        for x in range(l, r + 1):
8            for y in range(l, r + 1):
9                if x < y:
10                    dp[i + 1][0][y] = (dp[i + 1][0][y] + dp[i][1][x]) % mod
11                elif x > y:
12                    dp[i + 1][1][y] = (dp[i + 1][1][y] + dp[i][0][x]) % mod
13    return sum(dp[n][0][l:r + 1]) + sum(dp[n][1][l:r + 1]) % mod

Complexity note: The complexity arises from filling the DP table, iterating through all possible values in the range for each length.

  • 1Adjacent elements must differ.
  • 2Three consecutive elements cannot form increasing/decreasing sequences.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.