Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
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.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.
Example 1:
Input: nums = [2,3,4,3,4]
Output: 4
Explanation:
The alternating subarrays are [2, 3], [3,4], [3,4,3], and [3,4,3,4]. The longest of these is [3,4,3,4], which is of length 4.
Example 2:
Input: nums = [4,5,6]
Output: 2
Explanation:
[4,5] and [5,6] are the only two alternating subarrays. They are both of length 2.
Constraints:
2 <= nums.length <= 1001 <= nums[i] <= 104Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
[2,3,4,3,4]
[4,5,6]
longest-turbulent-subarray)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2765: Longest Alternating Subarray
class Solution {
public int alternatingSubarray(int[] nums) {
int ans = -1, n = nums.length;
for (int i = 0; i < n; ++i) {
int k = 1;
int j = i;
for (; j + 1 < n && nums[j + 1] - nums[j] == k; ++j) {
k *= -1;
}
if (j - i + 1 > 1) {
ans = Math.max(ans, j - i + 1);
}
}
return ans;
}
}
// Accepted solution for LeetCode #2765: Longest Alternating Subarray
func alternatingSubarray(nums []int) int {
ans, n := -1, len(nums)
for i := range nums {
k := 1
j := i
for ; j+1 < n && nums[j+1]-nums[j] == k; j++ {
k *= -1
}
if t := j - i + 1; t > 1 && ans < t {
ans = t
}
}
return ans
}
# Accepted solution for LeetCode #2765: Longest Alternating Subarray
class Solution:
def alternatingSubarray(self, nums: List[int]) -> int:
ans, n = -1, len(nums)
for i in range(n):
k = 1
j = i
while j + 1 < n and nums[j + 1] - nums[j] == k:
j += 1
k *= -1
if j - i + 1 > 1:
ans = max(ans, j - i + 1)
return ans
// Accepted solution for LeetCode #2765: Longest Alternating Subarray
fn alternating_subarray(nums: Vec<i32>) -> i32 {
let len = nums.len();
let mut ret = -1;
for i in 0..len {
let mut diff = 1;
let mut n = 1;
for j in (i + 1)..len {
if nums[j] - nums[j - 1] == diff {
n += 1;
} else {
break;
}
diff = if diff == 1 { -1 } else { 1 }
}
if n != 1 {
ret = std::cmp::max(ret, n);
}
}
ret
}
fn main() {
let nums = vec![2, 3, 4, 3, 4];
let ret = alternating_subarray(nums);
println!("ret={ret}");
}
#[test]
fn test_alternating_subarray() {
{
let nums = vec![2, 3, 4, 3, 4];
let ret = alternating_subarray(nums);
assert_eq!(ret, 4);
}
{
let nums = vec![4, 5, 6];
let ret = alternating_subarray(nums);
assert_eq!(ret, 2);
}
{
let nums = vec![1, 1, 1];
let ret = alternating_subarray(nums);
assert_eq!(ret, -1);
}
}
// Accepted solution for LeetCode #2765: Longest Alternating Subarray
function alternatingSubarray(nums: number[]): number {
let ans = -1;
const n = nums.length;
for (let i = 0; i < n; ++i) {
let k = 1;
let j = i;
for (; j + 1 < n && nums[j + 1] - nums[j] === k; ++j) {
k *= -1;
}
if (j - i + 1 > 1) {
ans = Math.max(ans, j - i + 1);
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.