Longest Alternating Subarray - Problem

You are given a 0-indexed integer array nums. A subarray s of length m is called alternating if:

  • m is greater than 1.
  • s[1] = s[0] + 1.
  • The 0-indexed subarray s looks 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 to s[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
Longest Alternating Subarray ProblemFind the longest subarray with alternating +1, -1, +1, -1... differences454547+1-1+1-1+3Valid Alternating PatternPattern: 4→5→4→5→4 with differences +1, -1, +1, -1Output: 5 (length of longest alternating subarray)
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
Asked in
Google 15 Microsoft 12 Amazon 8
12.5K Views
Medium Frequency
~15 min Avg. Time
287 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen