Longest Alternating Subarray - Problem
You are given a 0-indexed integer array nums. Your task is to find the longest alternating subarray within this array.
An alternating subarray is a contiguous sequence that follows a specific zigzag pattern:
- It must have length β₯ 2
- The second element equals the first element + 1
- Elements alternate between two values:
[a, a+1, a, a+1, a, a+1, ...]
Example: In array [2, 3, 2, 3, 2, 4], the subarray [2, 3, 2, 3, 2] is alternating with length 5.
Goal: Return the maximum length of any alternating subarray, or -1 if none exists.
Input & Output
example_1.py β Basic Alternating Pattern
$
Input:
[2, 3, 2, 3, 2]
βΊ
Output:
5
π‘ Note:
The entire array forms an alternating pattern: starts with 2, next is 3 (2+1), then alternates between 2 and 3. Length is 5.
example_2.py β Multiple Patterns
$
Input:
[4, 5, 4, 5, 6, 7, 6]
βΊ
Output:
4
π‘ Note:
Two alternating patterns exist: [4,5,4,5] with length 4, and [6,7,6] with length 3. Maximum is 4.
example_3.py β No Alternating Pattern
$
Input:
[1, 3, 2, 4]
βΊ
Output:
-1
π‘ Note:
No valid alternating pattern exists. For alternating pattern, second element must be first + 1, but we have 3 β 1+1.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Pattern Start
Find where OFF switch is followed by ON switch (value + 1)
2
Extend Pattern
Continue as long as switches alternate: OFF-ON-OFF-ON...
3
Pattern Breaks
When alternation stops, record length and search for new pattern
4
Find Maximum
Return the longest alternating sequence found
Key Takeaway
π― Key Insight: We can solve this efficiently in one pass by extending alternating patterns when we find them, rather than checking all possible subarrays.
Time & Space Complexity
Time Complexity
O(n)
Single pass through the array, each element visited once
β Linear Growth
Space Complexity
O(1)
Only using a few variables to track current and maximum lengths
β Linear Space
Constraints
- 1 β€ nums.length β€ 105
- -109 β€ nums[i] β€ 109
- Alternating subarray must have length β₯ 2
- Second element must equal first element + 1
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code