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
Light Switches: [2, 3, 2, 3, 2, 4, 5, 4]2OFF3ON2OFF3ON2OFF4BREAK5ON4OFFLongest Alternating Pattern: Length 5New Pattern: Length 3πŸ” Step 1: Find OFFβ†’ON transition (2β†’3)πŸ“ˆ Step 2: Extend pattern: 2β†’3β†’2β†’3β†’2 (Length: 5)⚠️ Step 3: Pattern breaks at 4 (expected 3)πŸ”„ Step 4: Start new pattern 4β†’5β†’4 (Length: 3)πŸ† Result: Maximum length = 5
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

n
2n
βœ“ Linear Growth
Space Complexity
O(1)

Only using a few variables to track current and maximum lengths

n
2n
βœ“ Linear Space

Constraints

  • 1 ≀ nums.length ≀ 105
  • -109 ≀ nums[i] ≀ 109
  • Alternating subarray must have length β‰₯ 2
  • Second element must equal first element + 1
Asked in
Google 45 Meta 32 Amazon 28 Microsoft 25
37.5K Views
Medium Frequency
~18 min Avg. Time
1.3K 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