Longest Alternating Parity Subarray
Longest Alternating Parity Subarray requires the length of the longest contiguous segment where parity alternates at every step: even then odd, or odd then even. The moment two neighboring numbers have the same parity, the current alternating streak ends and a new streak can begin from the current position.
A direct linear scan is enough. Track current streak length and best length so far. For each index, compare parity with the previous value: if different, extend streak; if same, reset streak to one. For empty arrays, return zero. This approach is O(n), uses constant extra memory, and matches exactly what the checker evaluates.
Judge coverage includes perfect alternation across full arrays, arrays with no alternation at all, mixed patterns where streaks break and restart, and empty input. Return only the maximum length integer. The key implementation detail is parity comparison stability for negative and positive values alike; parity logic should remain consistent regardless of sign. With careful reset behavior and a single pass, the solution remains simple, fast, and deterministic on all supported input shapes.
To avoid hidden mistakes, compute parity with a consistent method and compare adjacent parity states rather than raw values. That keeps behavior stable for negative numbers and large integers alike. The final answer should represent the longest uninterrupted alternating run encountered during the scan.
Examples
The longest alternating subarray is [1,2,3], with length 3.
The entire array alternates odd-even-odd-even-odd-even.
No alternation occurs, so the maximum length is 1.
Algorithm Flow

Best Answers
class Solution {
public int longest_alternating_subarray(int[] nums) {
if (nums.length == 0) return 0;
int maxLen = 1, current = 1;
for (int i = 1; i < nums.length; i++) {
if (Math.abs(nums[i] % 2) != Math.abs(nums[i-1] % 2)) current++;
else current = 1;
maxLen = Math.max(maxLen, current);
}
return maxLen;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
