We are given an array of integers nums. We need to count the number of subarrays that have a "zigzag" pattern.
A zigzag pattern means that the elements in the subarray alternate between increasing and decreasing.
For example, [1,2,1] is zigzag because 1<2 and then 2>1.
Similarly, [2,1,2] is also zigzag because 2>1 and then 1<2.
However, note that a single element is trivially zigzag? Actually, the problem says "alternate increasing and decreasing", so for a single element there is no alternation?
But typically in such problems, a single element is considered a zigzag subarray because there's no violation. However, let's clarify:
The pattern for a subarray of length 1: there is no adjacent pair, so it's automatically alternating?
Actually, the definition says "alternate increasing and decreasing". For a single element, there are no two adjacent elements to compare, so we can consider it as trivially satisfying the condition?
But note: for a subarray of length 2, we need exactly one comparison and it must be either increasing or decreasing. But then the pattern doesn't alternate because there's only one comparison?
Wait, the pattern requires alternation. For two elements, we have one comparison. That comparison can be either increasing or decreasing, but then there's no alternation because there's only one change?
Actually, the typical definition of a zigzag (or up-down) sequence is that the differences between successive elements strictly alternate between positive and negative.
For a sequence of length 1, there are no differences, so it's vacuously true?
However, let's look at the example:
The problem statement: "elements alternate increasing and decreasing".
For a subarray of length 2: we have one comparison. It must be either increasing or decreasing, but then we don't have an alternation because we need at least two comparisons to alternate?
But note: if we have [1,2] then it's increasing, but then there's no next comparison to alternate? So is [1,2] a zigzag?
Actually, in the context of this problem, I think we are to consider subarrays of length at least 2? But wait, the example of [1,2,1] is given.
Let me think: the condition for a subarray to be zigzag is that for every i from 1 to n-2 (if n is the length), we have either:
nums[i] - nums[i-1] and nums[i+1] - nums[i] have opposite signs, and also note that we don't want zero differences?
Actually, the condition is that the adjacent differences must alternate in sign. So for a subarray of length 2, we have only one difference, so there's no alternation to check?
But then, is a two-element subarray zigzag?
Let me check: if we have [1,2], then the only comparison is 1<2, so it's increasing. But then we don't have a next comparison to alternate with.
So by the definition, we require the sequence to alternate, meaning that if we have at least two comparisons, they must alternate.
However, for a two-element subarray, we have only one comparison, so it cannot alternate? But then we have to decide.
Looking at typical problems:
In the "wiggle subsequence" problem, the definition is: a sequence is wiggle if the differences between successive numbers strictly alternate between positive and negative.
The first difference may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.
But note: the wiggle subsequence problem counts subsequences, not subarrays.
However, for subarrays, I've seen similar problems:
For example, Leetcode 376. Wiggle Subsequence (but that's subsequence).
There is also a problem about counting the number of wiggle subarrays?
Actually, I recall a problem: Count the number of subarrays that are wiggle (or zigzag).
In that case, for a subarray of length 1, it's usually counted as 1 because it's trivially wiggle?
But wait, the problem says "alternate increasing and decreasing", which implies at least two elements?
However, let's see: if we have a single element, there's no increasing or decreasing, so it doesn't alternate?
I think we need to look at the problem statement again:
"elements alternate increasing and decreasing" -> this suggests that we need at least two elements to have an alternation?
But then, what about two elements? We have one comparison, which is either increasing or decreasing, but we don't have an alternation because we need at least two comparisons to alternate?
Actually, the alternation is between consecutive comparisons. So for a sequence of length 2, we have one comparison, so it's not alternating?
But then, if we have three elements, we have two comparisons and they must have opposite signs.
However, there's a nuance: if we have two elements, it's either increasing or decreasing. That doesn't alternate because we don't have two comparisons to alternate.
So maybe the condition is that for every index i from 1 to n-2, we have (nums[i]-nums[i-1])*(nums[i+1]-nums[i]) < 0, and also we don't have zero differences?
But then for n=2, there is no i from 1 to n-2 (because n-2 = 0, so the set is empty). So the condition is vacuously true?
But wait, the condition for alternation is that the signs of consecutive differences must be opposite. For two elements, we have one difference, so there is no consecutive pair of differences.
So by that logic, a two-element subarray would satisfy the condition because there are no two consecutive differences that violate the alternation?
However, that would mean that every two-element subarray is zigzag? But that's not true because if we have [1,1] then the difference is 0, which is not positive or negative.
So we must also require that the differences are non-zero.
Let me formalize:
For a subarray of length 1: no differences, so it's considered zigzag? But wait, the problem says "alternate increasing and decreasing", so if there's only one element, there's no increasing or decreasing.
However, in the context of this problem, I think we should count single element subarrays? But then the example of [1,2,1] doesn't mention single elements.
Alternatively, maybe the problem intends to count only subarrays of length at least 2?
Without explicit examples, I have to assume.
But note: in the example [1,2,1] is given as a zigzag. That's length 3.
Let me think about the condition:
We want the subarray to be such that for every i in the range [1, n-2] (if n>=3), we have (nums[i]-nums[i-1]) and (nums[i+1]-nums[i]) have opposite signs (and non-zero).
But for n=2, we have only one difference. What about that? We might require that the two elements are not equal? But then is [1,2] a zigzag?
Actually, in the pattern, we are alternating. For two elements, we have only one change. That change can be either up or down, and then we stop.
So I think for two elements, it's considered zigzag if they are not equal?
However, consider [1,2,3]: this is not zigzag because the differences are both positive (1<2 and 2<3).
So the condition for a subarray of length 3 is that the two differences have opposite signs.
Now, what about [1,2,2]?
The first difference: 1<2 -> positive.
The second difference: 2==2 -> zero -> not allowed?
So [1,2,2] is not zigzag.
Similarly, [2,1,1] is not zigzag.
So, let's define:
A subarray is zigzag if for every pair of consecutive differences (i.e., for every i from 1 to n-2), we have:
(nums[i] - nums[i-1]) * (nums[i+1] - nums[i]) < 0
and also, we must have that every adjacent pair is not equal? Because if any adjacent pair is equal, then one of the differences is zero, which breaks the condition?
Actually, the condition (nums[i]-nums[i-1])*(nums[i+1]-nums[i])<0 requires both differences to be non-zero and opposite signs.
So for a subarray of length 2, we don't have two consecutive differences, so we don't check that condition. But then we must ensure that the two elements are not equal?
Wait, the condition for a two-element subarray: the only requirement is that the two elements are not equal? Because if they are equal, then we have a flat, which is not increasing or decreasing?
But the problem says "alternate increasing and decreasing". For two elements, we have one comparison. That comparison must be either increasing or decreasing. So they must be not equal.
So the condition for a subarray to be zigzag:
For every adjacent pair in the subarray, the two elements must not be equal.
And for every index i from 1 to len(subarray)-2, we have (sub[i] - sub[i-1]) and (sub[i+1] - sub[i]) have opposite signs.
However, note: if we have a subarray of length 1, then there are no adjacent pairs, so the first condition (no equal adjacent) is vacuously true?
And the second condition doesn't apply because there are no i in the range.
So by this, a single element would be zigzag.
But wait, the problem says "alternate increasing and decreasing". For a single element, there's no increasing or decreasing.
However, in the context of this problem, I think we should count single element subarrays?
Let me look for similar problems:
In Leetcode 376 (Wiggle Subsequence), the definition says: "A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative."
And then: "The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence."
So by that, a sequence of 1 element is wiggle.
But note: the problem here is about subarrays (contiguous) and not subsequences.
However, the same logic might apply: a subarray of length 1 is trivially zigzag.
But then, what about two elements?
In the wiggle subsequence problem, a sequence of two elements is wiggle if the two elements are not equal.
Because we have one difference and that's it. There's no alternation required because we only have one difference.
So for our problem, I think we should follow the same:
Conditions for a subarray to be zigzag:
Let the subarray be of length L.
If L == 1: it is zigzag.
If L >= 2:
For every adjacent pair (i.e., for every i from 0 to L-2), we must have nums[i] != nums[i+1].
And for every i from 1 to L-2, we must have (nums[i] - nums[i-1]) and (nums[i+1] - nums[i]) have opposite signs.
However, note that the condition for L=2: we only require that the two elements are not equal. There's no alternation condition because we only have one difference.
So the algorithm:
We want to count all contiguous subarrays that satisfy the above.
How to do it efficiently?
We can try to use a two-pointer or dynamic programming.
Idea:
Let's define an array dp where dp[i] is the length of the longest zigzag subarray ending at index i.
But note: we want to count all subarrays, not just the longest.
Alternatively, we can think about extending a zigzag subarray ending at i.
However, note that a zigzag subarray must have the property that the differences alternate.
Let me define:
up[i] = length of the longest zigzag subarray ending at i and the last difference is positive (i.e., nums[i] > nums[i-1]).
down[i] = length of the longest zigzag subarray ending at i and the last difference is negative (i.e., nums[i] < nums[i-1]).
But note: for a subarray of length 1, we don't have a last difference. So we can set:
up[0] = 1, down[0] = 1.
Then for i>=1:
If nums[i] > nums[i-1]:
Then we can extend a subarray that ended at i-1 with a negative difference?
Because we want the last difference to be positive, so the previous difference (if exists) must be negative.
So: up[i] = down[i-1] + 1
But what about down[i]? We cannot extend because the last difference is positive, so down[i] = 1 (just the single element).
If nums[i] < nums[i-1]:
Then down[i] = up[i-1] + 1
and up[i] = 1.
If nums[i] == nums[i-1]:
Then both up[i] and down[i] = 1 (because we cannot extend any zigzag subarray that ended at i-1 with a non-zero difference? Actually, if we have equal, then we break the zigzag. So we start over with a new subarray of length 1? But wait, if we have [1,2,2], then at the second 2, we have nums[i]==nums[i-1], so we set up[i]=1 and down[i]=1? But then the subarray [2,2] is not zigzag because the two elements are equal. So we don't want to count that. So we set up[i]=1 and down[i]=1, meaning that the longest zigzag ending at i is just the single element (because we cannot extend the previous one). But then when we count, we will count the single element? That's okay.
However, note: the condition for a two-element subarray [a,b] is that a != b. So when we have nums[i] != nums[i-1], then we can have a two-element subarray that is zigzag?
But in our dp, when we set up[i] = down[i-1] + 1, if down[i-1] is 1 (meaning the subarray ending at i-1 is just a single element), then up[i] becomes 2. That two-element subarray [nums[i-1], nums[i]] is zigzag because they are not equal and we have only one difference (which is positive). So that's correct.
But wait: our dp definition: up[i] is the length of the longest zigzag subarray ending at i and with the last difference positive.
So for a two-element subarray [a,b] with a<b, then at index i (which is the index of b), we have up[i]=2 and down[i]=1.
Similarly, for [b,a] with b>a, then down[i]=2 and up[i]=1.
Now, what about three elements?
Example: [1,2,1]
i=0: up[0]=1, down[0]=1.
i=1: nums[1]=2 > nums[0]=1 -> up[1] = down[0]+1 = 2, down[1]=1.
i=2: nums[2]=1 < nums[1]=2 -> down[2] = up[1]+1 = 3, up[2]=1.
So we get down[2]=3, which is the length of the zigzag subarray [1,2,1].
But note: we also have other subarrays ending at 2: [2,1] and [1].
How do we count all subarrays?
We can use the dp arrays to count the number of zigzag subarrays ending at each index.
But note: the dp arrays give the longest zigzag subarray ending at i. However, we want to count every zigzag subarray.
Observation:
For a given ending index i, the zigzag subarrays ending at i are exactly the ones that are the suffixes of the longest zigzag subarray ending at i?
Actually, not necessarily. Because the condition for a subarray to be zigzag is local: it depends on the consecutive differences.
But note: if we have a long zigzag subarray ending at i, then every suffix of that subarray (starting at some j and ending at i) is also zigzag?
Let me check:
Suppose we have a zigzag subarray from index j to i. Then if we take a suffix starting at k (where j<k<=i), then the subarray from k to i must also be zigzag?
Because the condition for being zigzag is about consecutive differences. If the whole array from j to i is zigzag, then the consecutive differences from k to i are a consecutive part of the alternating sequence. But wait:
Example: [1,2,1] is zigzag. The suffix [2,1] is also zigzag (one difference, negative). The suffix [1] is trivially zigzag.
But what about [1,2,1,2]?
[1,2,1,2]:
differences: +, -, + -> alternating. So it's zigzag.
Suffixes:
[1,2,1,2] -> zigzag
[2,1,2] -> zigzag (differences: -, +)
[1,2] -> zigzag (difference: +)
[2] -> zigzag
So every suffix of a zigzag subarray is also zigzag.
What about a non-suffix? Actually, if we have a zigzag subarray from j to i, then any contiguous subarray within that (not necessarily suffix) is also zigzag?
Example: [1,2,1,2] and take [1,2,1] -> that's a prefix of the suffix? Actually, it's a subarray from index 0 to 2. It's zigzag.
But wait, what if we have [1,2,1,0]?
[1,2,1,0]:
differences: +, -, - -> not alternating because the last two are both negative.
So the whole is not zigzag. But the subarray [1,2,1] is zigzag and [2,1,0] is not?
Actually, [2,1,0] has differences: -, - -> not alternating.
So if the whole subarray is not zigzag, then we cannot say that every subarray within it is zigzag.
But if a subarray is zigzag, then every contiguous subarray of it is also zigzag?
Let's prove:
Suppose we have a zigzag subarray from j to i. Then for any k and l with j <= k < l <= i, we want to show that the subarray from k to l is zigzag.
The condition for the subarray from k to l is that for every index m from k+1 to l-1, we have (nums[m]-nums[m-1]) and (nums[m+1]-nums[m]) have opposite signs.
But since the whole array from j to i is zigzag, we know that for every m from j+1 to i-1, the condition holds.
Now, for the subarray from k to l, the indices m we consider are from k+1 to l-1, which are a subset of [j+1, i-1] (if j<k and l<i). So the condition holds for those m as well.
Additionally, we must check that within the subarray from k to l, there are no equal adjacent elements?
But note: if the whole array from j to i has no equal adjacent elements? Actually, the condition for zigzag requires that every adjacent pair in the whole subarray is not equal?
Wait, we didn't state that explicitly. But if we have an equal adjacent pair, then one of the differences is zero, which breaks the condition (because we require the product of consecutive differences to be negative, which requires non-zero).
So in a zigzag subarray, by definition, every adjacent pair must be unequal.
Therefore, the subarray from k to l also has every adjacent pair unequal because they are a subset.
So yes, if a subarray is zigzag, then every contiguous subarray of it is also zigzag.
Therefore, for a given ending index i, the set of zigzag subarrays ending at i are exactly the suffixes of the longest zigzag subarray ending at i.
How many such suffixes?
If the longest zigzag subarray ending at i has length L, then we have L subarrays ending at i:
one of length 1 (just the last element),
one of length 2 (last two),
...,
one of length L (the whole longest).
But wait: is that always true?
Consider the example: [1,2,1,0] and i=3 (the last element 0).
The longest zigzag subarray ending at 3?
We have:
[0] -> length 1
[1,0] -> length 2, and 1>0 -> negative difference -> zigzag?
[2,1,0] -> differences: 2>1 (negative) and 1>0 (negative) -> not alternating.
[1,2,1,0] -> not zigzag.
So the longest zigzag ending at 3 is [1,0] of length 2.
Then the suffixes of [1,0] are: [0] and [1,0]. Both are zigzag?
[0] -> zigzag.
[1,0] -> zigzag because 1>0 and only one difference.
So we have 2 subarrays ending at 3.
But note: there is also the subarray [0] which we already counted.
So indeed, the number of zigzag subarrays ending at i is equal to the length of the longest zigzag subarray ending at i.
Therefore, we can compute for each i the length of the longest zigzag subarray ending at i (let's call it dp[i]), and then the total count is the sum of dp[i] for all i.
But wait: is dp[i] defined as the length of the longest zigzag subarray ending at i?
We have two types: up and down. But note that a zigzag subarray ending at i can have either last difference positive or negative.
Actually, the longest zigzag subarray ending at i is max(up[i], down[i]).
But note: up[i] and down[i] are defined as the longest zigzag subarray ending at i with the last difference being positive or negative respectively.
However, consider:
If we have a subarray that ends at i and has last difference positive, then it is counted in up[i].
Similarly for down[i].
But note: a subarray of length 1 (just the element at i) is counted in both up[i] and down[i]?
We set up[0]=1 and down[0]=1. But that means we are counting the same subarray twice?
Actually, for a single element, there is no last difference. So we are arbitrarily assigning it to both?
But then when we take max(up[i], down[i]) for i=0, we get 1. That's correct.
However, for i>0:
If nums[i] > nums[i-1], then up[i] = down[i-1] + 1, and down[i] = 1.
So the longest ending at i is up[i].
If nums[i] < nums[i-1], then down[i] = up[i-1] + 1, and up[i] = 1.
So the longest ending at i is down[i].
If nums[i] == nums[i-1], then both are 1.
So in all cases, the longest zigzag subarray ending at i is exactly max(up[i], down[i]).
But wait: what if we have a longer subarray that ends at i and has the opposite last difference?
Example: [1,2,1,2] at i=3 (the last 2).
i=0: up[0]=1, down[0]=1.
i=1: nums[1]>nums[0] -> up[1]=down[0]+1=2, down[1]=1.
i=2: nums[2]<nums[1] -> down[2]=up[1]+1=3, up[2]=1.
i=3: nums[3]>nums[2] -> up[3]=down[2]+1=4, down[3]=1.
So the longest ending at 3 is 4, which is correct.
Therefore, we can compute dp[i] = max(up[i], down[i]) and then sum dp[i] for i from 0 to n-1.
However, note: the single element subarrays are counted in dp[i] (as 1). And that's what we want?
We want to count every zigzag subarray. And we argued that for each ending index i, the number of zigzag subarrays ending at i is exactly the length of the longest one.
But wait: is it always true that every suffix of the longest zigzag subarray ending at i is zigzag?
We proved that if a subarray is zigzag, then every contiguous subarray of it is zigzag.
So the longest zigzag subarray ending at i, say of length L, then we have L suffixes (of lengths 1 to L) and each is zigzag.
And are there any other zigzag subarrays ending at i?
Suppose there is a zigzag subarray ending at i that is not a suffix of the longest one.
Let that subarray be from index j to i, and suppose j is greater than the start index of the longest one (so it's shorter).
But then that subarray is a suffix of the longest one?
Actually, if the longest one starts at s, then any subarray ending at i that starts at j>=s is a suffix of the longest one?
Wait: the longest one is from s to i. Then a subarray from j to i (with j>=s) is exactly the suffix of the longest one starting at j.
So indeed, every zigzag subarray ending at i is a suffix of the longest one.
Therefore, the number of zigzag subarrays ending at i is exactly the length of the longest zigzag subarray ending at i.
So the algorithm:
Initialize:
up[0] = 1, down[0] = 1.
total = up[0] (or down[0], same) -> 1.
For i from 1 to n-1:
if nums[i] > nums[i-1]:
up[i] = down[i-1] + 1
down[i] = 1
elif nums[i] < nums[i-1]:
down[i] = up[i-1] + 1
up[i] = 1
else: // equal
up[i] = 1
down[i] = 1
total += max(up[i], down[i])
But wait: what about the case when we have a two-element subarray?
For i=1, if nums[1] != nums[0], then we get either up[1]=2 or down[1]=2, and then we add 2 to total.
That counts:
[nums[1]] (length 1) and [nums[0], nums[1]] (length 2).
But note: we also count the subarray [nums[0]] at i=0. So we are counting every single element once, and then for every i>0 we count the new subarrays that end at i.
However, let's check with a simple example: [1,2]
i=0: up[0]=1, down[0]=1, total=1.
i=1: nums[1]=2 > nums[0]=1 -> up[1]=down[0]+1=2, down[1]=1.
total += max(2,1) -> total=1+2=3.
But the zigzag subarrays of [1,2] are:
[1] -> yes
[2] -> yes
[1,2] -> yes (because 1<2, and only one difference, so it's increasing and that's allowed? Actually, by our condition, for two elements we require they are not equal, which they aren't.)
So we have 3 subarrays. Our algorithm gives 3.
But wait, is [1,2] really zigzag?
According to the condition: for two elements, we don't have two consecutive differences to alternate. So we only require that the two elements are not equal.
So yes.
Another example: [1,2,1]
i=0: up[0]=1, down[0]=1, total=1.
i=1: up[1]=2, down[1]=1, total=1+2=3.
i=2: nums[2]=1 < nums[1]=2 -> down[2]=up[1]+1=3, up[2]=1, total=3+3=6.
The zigzag subarrays of [1,2,1] are:
[1] (at index0)
[2] (at index1)
[1] (at index2) -> but wait, we have two [1]? Actually, the array has two 1's at index0 and index2.
So the single element subarrays: [1] (index0), [2], [1] (index2) -> 3.
Two-element: [1,2] (indices0-1), [2,1] (indices1-2) -> 2.
Three-element: [1,2,1] -> 1.
Total 6.
So it matches.
Example with equal elements: [1,1]
i=0: up[0]=1, down[0]=1, total=1.
i=1: nums[1]==nums[0] -> up[1]=1, down[1]=1, total=1+1=2.
The zigzag subarrays:
[1] (index0) -> 1
[1] (index1) -> 1
[1,1] -> not zigzag because the two elements are equal?
So we have 2.
But wait, our condition: for two elements, we require they are not equal. So [1,1] is not counted.
Our algorithm: at i=1, we set up[1]=1 and down[1]=1, then we add 1 (because max=1).
That means we are only counting the single element at index1?
But we already counted the single element at index0.
So total 2, which is correct: two single elements.
Example: [1,2,2,1]
i=0: up[0]=1, down[0]=1, total=1.
i=1: 2>1 -> up[1]=2, down[1]=1, total=1+2=3.
i=2: 2==2 -> up[2]=1, down[2]=1, total=3+1=4.
i=3: 1<2 -> down[3]=up[2]+1=2, up[3]=1, total=4+2=6.
Now, list all zigzag subarrays:
[1] (0)
[2] (1)
[2] (2)
[1] (3) -> 4 single elements.
Two-element:
[1,2] (0-1) -> yes
[2,2] (1-2) -> no
[2,1] (2-3) -> yes? Wait, [2,1] from indices2-3: 2>1 -> decreasing, so yes.
So two-element: [1,2] and [2,1] -> 2.
Three-element:
[1,2,2] -> no (because 2==2)
[2,2,1] -> no (because 2==2)
Four-element: [1,2,2,1] -> no.
So total 4+2 = 6.
Our algorithm gives 6.
So it seems correct.
However, note: in the example [1,2,2,1], at i=3 we have down[3]=2. That corresponds to the subarray [2,1] (indices2-3) of length 2.
But wait, the longest zigzag ending at index3 is [2,1] (length2). Then we count the two suffixes: [1] and [2,1].
But note: [2,1] ends at index3, and [1] is the single element at index3.
So we are counting the single element at index3 again?
But we already counted the single element at index3 in the step for i=3?
Actually, at each i, we are counting the zigzag subarrays that end at i.
So for i=3, we count:
[1] (index3) -> 1
[2,1] (indices2-3) -> 1
So that's 2.
And at i=2, we counted:
[2] (index2) -> 1
So the single element at index2 is counted at i=2, and the single element at index3 is counted at i=3.
That's correct because they are different subarrays.
Therefore, the algorithm is:
function countZigZag(nums):
n = len(nums)
if n == 0: return 0
up = [1] * n
down = [1] * n
total = 1 // for the first element
for i in range(1, n):
if nums[i] > nums[i-1]:
up[i] = down[i-1] + 1
down[i] = 1
elif nums[i] < nums[i-1]:
down[i] = up[i-1] + 1
up[i] = 1
else:
up[i] = 1
down[i] = 1
total += max(up[i], down[i])
return total
But wait: what about the first element? We set total=1 for the first element. Then in the loop we start from i=1.
Alternatively, we can set total=0 and then in the loop we add for each i.
However, note that for i=0, we have up[0]=down[0]=1, so we should add 1 for i=0.
So we can do:
total = 0
for i in range(n):
if i==0:
up[i] = 1
down[i] = 1
else:
... (the same)
total += max(up[i], down[i])
But the above code already sets up[0]=down[0]=1 and then we start the loop from i=1, so we have to account for i=0 separately.
Alternatively, we can initialize up and down arrays and then loop from 1 to n-1, and then add the first element.
Let me write:
n = len(nums)
if n == 0: return 0
up = [1] * n
down = [1] * n
total = 1 # for i=0
for i in range(1, n):
... (the same)
total += max(up[i], down[i])
But wait: at i=0, we have max(up[0], down[0]) = 1, so we are already counting it in total?
Actually, we set total=1 and then we add from i=1. So we are counting the first element once.
Alternatively, we can do:
total = 0
for i in range(n):
if i==0:
up[i] = 1
down[i] = 1
else:
...
total += max(up[i], down[i])
That would work too.
Let's test with [1,2,1] again:
i=0: up[0]=1, down[0]=1, total=1.
i=1: nums[1]>nums[0] -> up[1]=down[0]+1=2, down[1]=1, total=1+2=3.
i=2: nums[2]<nums[1] -> down[2]=up[1]+1=3, up[2]=1, total=3+3=6.
So it's correct.
But note: what if we have a sequence that is strictly increasing?
Example: [1,2,3,4]
i=0: total=1.
i=1: 2>1 -> up[1]=2, down[1]=1 -> total=1+2=3.
i=2: 3>2 -> up[2]=down[1]+1=2, down[2]=1 -> total=3+2=5.
i=3: 4>3 -> up[3]=down[2]+1=2, down[3]=1 -> total=5+2=7.
Now, list the zigzag subarrays for [1,2,3,4]:
Single elements: 4 -> 4.
Two-element: [1,2], [2,3], [3,4] -> 3.
Three-element: [1,2,3] -> not zigzag because 1<2 and 2<3 (both positive) -> no.
[2,3,4] -> same -> no.
Four-element: [1,2,3,4] -> no.
So total 4+3=7.
Our algorithm gives 7.
How?
At i=0: [1] -> 1
At i=1: [2] and [1,2] -> 2
At i=2: [3] and [2,3] -> 2 (note: [1,2,3] is not counted because at i=2, up[2]=2, which corresponds to [2,3] and [3]. The longest ending at 2 is [2,3] of length 2? But wait, we have [1,2,3] is not zigzag, so the longest ending at 2 is [2,3]?
Actually, at i=2, we have:
up[2] = down[1] + 1 = 1+1=2 -> that means the longest zigzag ending at 2 with last difference positive is of length 2: [2,3] (since 2<3).
down[2]=1.
So we count [3] and [2,3] -> 2.
At i=3: similarly, [4] and [3,4] -> 2.
Total: 1+2+2+2=7.
So it works.
Therefore, the algorithm is correct.
However, note: the condition for a two-element subarray is that the two elements are not equal.
In the strictly increasing case, every two-element subarray is zigzag?
[1,2]: 1<2 -> one positive difference -> allowed.
So yes.
What about a sequence that is strictly decreasing? Similarly.
So the algorithm works for all cases.
Let's code accordingly.
But note: the problem says "alternate increasing and decreasing".
In our condition, we require that consecutive differences have opposite signs.
That means if we have a sequence of three elements, it must be either up-down or down-up.
And for two elements, it's either up or down.
And for one element, it's always allowed.
So we are good.
Complexity: O(n) time and O(n) space. But we can reduce space to O(1) by only keeping the previous up and down.
Let's do:
prev_up = 1
prev_down = 1
total = 1
for i from 1 to n-1:
if nums[i] > nums[i-1]:
up = prev_down + 1
down = 1
elif nums[i] < nums[i-1]:
down = prev_up + 1
up = 1
else:
up = 1
down = 1
total += max(up, down)
prev_up = up
prev_down = down
But wait: we are using prev_up and prev_down from the previous iteration.
However, note that in the case of equal, we set both to 1, so that's fine.
Let's test with [1,2,1] using the O(1) space:
i=0: prev_up=1, prev_down=1, total=1.
i=1: nums[1]>nums[0] -> up = prev_down+1 = 2, down=1.
total += max(2,1)=2 -> total=3.
then set prev_up=2, prev_down=1.
i=2: nums[2]<nums[1] -> down = prev_up+1 = 3, up=1.
total += max(1,3)=3 -> total=6.
set prev_up=1, prev_down=3.
So it works.
Therefore, we can write:
function countZigZag(nums):
n = len(nums)
if n == 0: return 0
total = 1
up = 1
down = 1
for i in range(1, n):
if nums[i] > nums[i-1]:
up = down + 1
down = 1
elif nums[i] < nums[i-1]:
down = up + 1
up = 1
else:
up = 1
down = 1
total += max(up, down)
return total
However, note: in the first iteration (i=1), we use the initial values of up and down (which are 1 and 1).
That's correct because for i=0, we have up=1, down=1.
But wait: in the code above, we set total=1 for the first element. Then for i=1, we compute new up and down and then add.
Let me test with [1,2] again:
n=2, total=1.
i=1: nums[1]=2>1 -> up = down+1 = 1+1=2, down=1.
total += max(2,1)=2 -> total=3.
Correct.
But what about [1,1]?
total=1.
i=1: nums[1]==nums[0] -> up=1, down=1.
total += 1 -> total=2.
Correct.
So this is the final algorithm.
However, note: the problem says "subarrays", and we are counting every contiguous subarray that satisfies the condition.
Let me run through [1,2,3,4] with the O(1) code:
total=1.
i=1: 2>1 -> up=1+1=2, down=1; total=1+2=3.
i=2: 3>2 -> up=down(prev=1)+1=2, down=1; total=3+2=5.
i=3: 4>3 -> up=down(prev=1)+1=2, down=1; total=5+2=7.
Correct.
One more: [1,2,1,2]
total=1.
i=1: 2>1 -> up=2, down=1; total=3.
i=2: 1<2 -> down=up(prev=2)+1=3, up=1; total=3+3=6.
i=3: 2>1 -> up=down(prev=3)+1=4, down=1; total=6+4=10.
Now, list all zigzag subarrays of [1,2,1,2]:
Length 1: 4 (each element)
Length 2: [1,2], [2,1], [1,2] (indices2-3) -> 3? Wait, [1,2] at indices0-1 and [1,2] at indices2-3 are two different subarrays.
So: [1,2] (0-1), [2,1] (1-2), [1,2] (2-3) -> 3.
Length 3: [1,2,1] (0-2), [2,1,2] (1-3) -> 2.
Length 4: [1,2,1,2] -> 1.
Total: 4+3+2+1=10.
So correct.
Therefore, the algorithm is:
def count_zigzag_subarrays(nums):
n = len(nums)
if n == 0:
return 0
total = 1
up = 1
down = 1
for i in range(1, n):
if nums[i] > nums[i-1]:
up = down + 1
down = 1
elif nums[i] < nums[i-1]:
down = up + 1
up = 1
else:
up = 1
down = 1
total += max(up, down)
return total
However, note: the condition for a two-element subarray is that they are not equal.
In our code, when nums[i] != nums[i-1], we set either up or down to the previous opposite plus one.
But what about when we have a two-element subarray that is the first two?
That is handled: at i=1, we use the initial up and down (which are 1) and then set up=2 or down=2.
Then we add 2, which counts the two-element and the single element at i=1.
But wait: the single element at i=1 is counted at every i?
Yes, because for each i, we are counting the zigzag subarrays that end at i.
And the single element at i is one of them.
So we are counting every single element exactly once (at its own index).
And every multi-element subarray is counted exactly once, at its ending index.
Therefore, the algorithm is correct.
Let's write the code accordingly.
But note: the problem may have a constraint on the array length? We assume it's reasonable.
Time complexity: O(n)
Space complexity: O(1)
We'll implement the function as described.
However, note: the problem says "write a function", so we assume we are to return the count.
Let me test with a few more:
Example: [1]
n=1: total=1 -> correct.
Example: [1,2,2,3]
i=0: total=1.
i=1: 2>1 -> up=2, down=1; total=3.
i=2: 2==2 -> up=1, down=1; total=4.
i=3: 3>2 -> up=down(prev=1)+1=2, down=1; total=4+2=6.
Now list:
[1], [2] (index1), [2] (index2), [3] -> 4.
Two-element: [1,2] (0-1), [2,2] (1-2) -> no, [2,3] (2-3) -> yes.
So two-element: [1,2] and [2,3] -> 2.
Three-element: [1,2,2] -> no, [2,2,3] -> no.
Four-element: [1,2,2,3] -> no.
Total 6.
Correct.
Example: [3,2,1]
i=0: total=1.
i=1: 2<3 -> down=up(prev=1)+1=2, up=1; total=1+2=3.
i=2: 1<2 -> down=up(prev=1)+1=2, up=1; total=3+2=5.
List:
[3],[2],[1] -> 3.
Two-element: [3,2] and [2,1] -> 2.
Three-element: [3,2,1] -> not zigzag because 3>2 and 2>1 (both negative) -> no.
Total 5.
Correct.
So the algorithm is solid.
We'll implement accordingly.
However, note: the condition for a subarray to be zigzag is that the differences alternate.
Our dp exactly captures that.
Final code:
To solve this problem, we need to count the number of contiguous subarrays in a given array of integers that exhibit a "zigzag" pattern. A subarray has a zigzag pattern if the differences between consecutive elements alternate in sign (positive, negative, positive, etc., or negative, positive, negative, etc.). Additionally, any two consecutive elements must not be equal, as a zero difference breaks the alternation. Single-element subarrays are trivially considered zigzag.
Approach
- Problem Analysis: The key observation is that for any ending index
i, the number of zigzag subarrays ending at i equals the length of the longest zigzag subarray ending at i. This is because every suffix of a zigzag subarray is also zigzag.
- Dynamic Programming Insight: We maintain two variables,
up and down, representing the lengths of the longest zigzag subarrays ending at the current index with the last difference being positive or negative, respectively.
- Iteration: For each element from the second to the last:
- If the current element is greater than the previous, the last difference is positive. Hence,
up becomes down + 1 (extending a subarray ending with a negative difference) and down resets to 1.
- If the current element is smaller than the previous, the last difference is negative. Hence,
down becomes up + 1 and up resets to 1.
- If the current element equals the previous, both
up and down reset to 1 (only the single-element subarray remains).
- Counting: For each index, we add the maximum of
up and down to the total count, as this gives the number of zigzag subarrays ending at that index.
Solution Code
def count_zigzag_subarrays(nums):
n = len(nums)
if n == 0:
return 0
total = 1 # Count the first element
up = 1
down = 1
for i in range(1, n):
if nums[i] > nums[i-1]:
up = down + 1
down = 1
elif nums[i] < nums[i-1]:
down = up + 1
up = 1
else:
up = 1
down = 1
total += max(up, down)
return total
Explanation
- Initialization: Start with
total = 1 to account for the first element (single-element subarray). up and down are initialized to 1.
- Loop Through Array: For each subsequent element:
- If
nums[i] > nums[i-1], the current difference is positive. The longest zigzag subarray ending here with a positive last difference is one more than the longest ending with a negative difference (down + 1). The down counter resets to 1.
- If
nums[i] < nums[i-1], similarly, down becomes up + 1 and up resets to 1.
- If equal, both reset to 1 (only the single-element subarray is valid).
- Update Total: For each index, the number of new zigzag subarrays ending there is the length of the longest one (
max(up, down)), which is added to total.
- Result: After processing all elements,
total contains the count of all zigzag subarrays.
This approach efficiently computes the result in O(n) time with O(1) space, leveraging dynamic programming principles to avoid recomputation and利用 the property that all suffixes of a zigzag subarray are also zigzag.