All problems
0924HardMathDynamic Programming

Counting Alternating Runs of a Given Length

Tracked in this browser only
Write code

Trains the technique from

LeetCode 3700Number of ZigZag Arrays II

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A reading log is a list of n whole numbers, each between l and r inclusive.

The log alternates when every step from one reading to the next changes direction: it goes up, then down, then up, and so on, or down, then up, then down, and so on. No two neighbouring readings may be equal.

Return how many alternating logs there are, modulo 10^9 + 7.

Examples

Example 1

Input
n = 3, l = 1, r = 3
Output
10

Of the twenty-seven logs of three readings over 1, 2 and 3, ten alternate: five that go up then down and five that go down then up.

Example 2

Input
n = 3, l = 1, r = 2
Output
2

Only 1, 2, 1 and 2, 1, 2 alternate.

Example 3

Input
n = 7, l = 4, r = 9
Output
16544

Six readings are allowed and the log holds seven of them, and the count comes out of carrying the two families forward six steps.

Constraints

  • 3 <= n <= 10^9
  • 1 <= l < r <= 75

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def zig_zag_arrays(n: int, l: int, r: int) -> int:
Java
public int zigZagArrays(int n, int l, int r)
September 7
Apply