Problem Description
Given an integer array nums, find the maximum length of its contiguous subarrays that are alternating. A subarray is alternating if it has length m >= 2, the second element equals the first plus 1, and then the subarray alternates between two fixed values (i.e. follows the pattern [a, a+1, a, a+1, ...]). If no such subarray exists return -1.
Key Insights
- The alternating pattern is rigid: once we identify two consecutive numbers where nums[i+1] == nums[i] + 1, the alternating subarray should keep alternating between these two values.
- Once the pattern is broken, reset the alternating subarray length.
- A single pass over the array maintaining a current alternating subarray length is sufficient.
- Remember to check and update the maximum length found, and return -1 if no alternating subarray (length >= 2) is encountered.
Space and Time Complexity
Time Complexity: O(n) where n is the length of the array, since we only traverse the array once. Space Complexity: O(1) as only a few auxiliary variables are used regardless of input size.
Solution
We approach this problem with a single pass iteration over the array. We maintain a variable to track the current alternating subarray length. For each pair of consecutive elements, if the difference equals 1 and the expected alternating value (which alternates between a and a+1) matches, we extend the current alternating sequence. Otherwise, we check if the pair forms a valid start (i.e., nums[i+1] == nums[i]+1) and restart the count accordingly. We also update the maximum length along the way. Finally, if the maximum length is less than 2 (which would indicate no valid alternating subarray), we return -1.