BudiBadu Logo

Longest Alternating Parity Subarray

Array Medium 1 views
Like7

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

Example 1
Input
nums = [1,1,2,3]
Output
3
Explanation

The longest alternating subarray is [1,2,3], with length 3.

Example 2
Input
nums = [3,2,5,8,7,6]
Output
6
Explanation

The entire array alternates odd-even-odd-even-odd-even.

Example 3
Input
nums = [4,4,4,4]
Output
1
Explanation

No alternation occurs, so the maximum length is 1.

Algorithm Flow

Recommendation Algorithm Flow for Longest Alternating Parity Subarray - Budibadu
Recommendation Algorithm Flow for Longest Alternating Parity Subarray - Budibadu

Best Answers

java
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;
    }
}