Code Logo

Alternating Parity Check

Published atDate not available
Easy 0 views
Like0

In this problem, you look at a list of numbers and check whether the pattern keeps switching between even and odd. That means if one number is even, the next one should be odd. If one number is odd, the next one should be even.

You are not changing the list or sorting it. You are only checking the numbers in the order they already appear. The answer is just true or false. If the list breaks the pattern even once, the whole answer becomes false.

For example, [2,5,6,3] works because it goes even, odd, even, odd. But [1,3,5] does not work because the first two numbers are both odd, so the alternating pattern breaks right away. A list with only one number is always okay, and an empty list is okay too because nothing breaks the rule.

The most important thing is to compare neighbors. You do not need big calculations here. You just move through the list and ask, “Did the pattern switch this time?” If the answer stays yes all the way through, the list passes.

Example Input & Output

Example 1
Input
nums = [0]
Output
true
Explanation

A single element vacuously satisfies the alternating rule.

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

The sequence alternates even, odd, even, odd.

Example 3
Input
nums = [1,3,5]
Output
false
Explanation

Two odd numbers appear consecutively.

Algorithm Flow

Recommendation Algorithm Flow for Alternating Parity Check
Recommendation Algorithm Flow for Alternating Parity Check

Best Answers

java
class Solution {
    public boolean is_alternating(Object nums) {
        int[] arr = (int[]) nums;
        if (arr.length <= 1) {
            return true;
        }
        for (int i = 0; i < arr.length - 1; i++) {
            if ((arr[i] % 2) == (arr[i+1] % 2)) {
                return false;
            }
        }
        return true;
    }
}