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 INPUT nums = [4, 5, 4, 5, 6, 7] 4 i=0 5 i=1 4 i=2 5 i=3 6 i=4 7 i=5 Alternating Pattern: [a, a+1, a, a+1, ...] Differences: +1, -1, +1, -1... +1 -1 +1 +1 +1 Constraints: - Length m > 1 - s[1] = s[0] + 1 - Alternates: +1, -1, +1... ALGORITHM STEPS 1 Initialize maxLen = -1, currLen = 0 2 Iterate Array Check each pair 3 Check Pattern Verify +1/-1 alternation 4 Update Max Track longest valid subarray Trace: Single Pass i pair diff len max 0 4,5 +1 2 2 1 5,4 -1 3 3 2 4,5 +1 4 4 3 5,6 +1! reset 4 4 6,7 +1 2 4 end 4 FINAL RESULT Longest Alternating Subarray: 4 5 4 5 indices 0 to 3 +1 -1 +1 Output: 4 Verification: [OK] Length 4 > 1 [OK] 5 = 4 + 1 [OK] Pattern: +1, -1, +1 [OK] No longer valid subarray Key Insight: Single pass O(n) solution: Track expected difference (+1 or -1) and current length. When pattern breaks, check if new start is valid (diff=+1). The alternating pattern requires strict +1/-1 oscillation starting with +1. TutorialsPoint - Longest Alternating Subarray | Single Pass Optimization
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