#2765
Easy Algorithms Longest alternating subarray
Array Enumeration
35.1% acceptance
Feb 25, 2026
245
188
You are given a 0-indexed integer array nums. A subarray s of length m is called alternating if:
m is greater than 1.
s1 = s0 + 1.
The 0-indexed subarray s looks like [s0, s1, s0, s1,...,s(m-1) % 2]. In other words, s1 - s0 = 1, s2 - s1 = -1, s3 - s2 = 1, s4 - s3 = -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.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn alternating_subarray(nums: Vec<i32>) -> i32 {
let n = nums.len();
let mut res = -1i32;
for i in 0..n - 1 {
if nums[i + 1] - nums[i] == 1 {
let mut len = 2usize;
let mut j = i + 1;
while j + 1 < n {
// expected diff at step len-1:
// step 0: +1, step 1: -1, step 2: +1, ...
let expected = if len % 2 == 0 { -1 } else { 1 };
if nums[j + 1] - nums[j] == expected {
len += 1;
j += 1;
} else {
break;
}
}
res = res.max(len as i32);
}
}
res
}
}