Longest Alternating Subarray - Problem
You are given a 0-indexed integer array nums. A subarray s of length m is called alternating if:
mis greater than 1.s[1] = s[0] + 1.- The 0-indexed subarray
slooks like[s[0], s[1], s[0], s[1], ..., s[(m-1) % 2]]. In other words,s[1] - s[0] = 1,s[2] - s[1] = -1,s[3] - s[2] = 1,s[4] - s[3] = -1, and so on up tos[m - 1] - s[m - 2] = (-1)^m.
Return the maximum length of all alternating subarrays present in nums or -1 if no such subarray exists.
A subarray is a contiguous non-empty sequence of elements within an array.
Input & Output
Example 1 — Valid Alternating Pattern
$
Input:
nums = [4,5,4,5,6,7]
›
Output:
4
💡 Note:
The subarray [4,5,4,5] has length 4 and follows alternating pattern: 4→5 (+1), 5→4 (-1), 4→5 (+1)
Example 2 — No Valid Pattern
$
Input:
nums = [3,2,1,4]
›
Output:
-1
💡 Note:
No subarray satisfies the alternating pattern requirements (must start with +1 difference)
Example 3 — Multiple Valid Patterns
$
Input:
nums = [1,2,1,2,1]
›
Output:
5
💡 Note:
The entire array [1,2,1,2,1] forms a valid alternating pattern: 1→2 (+1), 2→1 (-1), 1→2 (+1), 2→1 (-1)
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Array with potential alternating sequences
2
Find Pattern
Look for +1, -1, +1, -1... differences
3
Return Length
Maximum length of valid alternating subarray
Key Takeaway
🎯 Key Insight: An alternating pattern must start with difference +1 and then strictly alternate between -1 and +1
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code