BudiBadu Logo

Alternating Parity Check

Array Easy 1 views
Like12

Imagine receiving a sequence of integers that represent alternating steps in a lab experiment—steady phases are even numbers, exploratory spikes are odd numbers. The protocol states that the readings must alternate strictly: even, odd, even, odd, and so on, or starting with odd and then even. Your task is to verify whether the array follows this rule from start to finish. If the pattern holds across the entire sequence, return true; otherwise, return false.

This check is like watching a pendulum swing. The pendulum should pass from one side to the other without repeating the same side twice in a row. If at any point the pendulum breaks rhythm—two even numbers back-to-back or two odd numbers in succession—the pattern fails. Empty arrays or arrays with a single element are considered valid because there is nothing to contradict the alternation.

Remember that negative numbers still have parity based on whether they are divisible by two. The challenge focuses on pattern recognition and careful traversal: scanning the array, you confirm that each pair of consecutive elements switches between even and odd. Return a boolean result that reflects the experiment’s adherence to the alternating parity protocol.

Example 1:

Input: nums = [2,5,6,3]
Output: true
Explanation: The sequence alternates even, odd, even, odd.

Example 2:

Input: nums = [1,3,5]
Output: false
Explanation: Two odd numbers appear consecutively.

Example 3:

Input: nums = [0]
Output: true
Explanation: A single element vacuously satisfies the alternating rule.

Algorithm Flow

Recommendation Algorithm Flow for Alternating Parity Check - Budibadu
Recommendation Algorithm Flow for Alternating Parity Check - Budibadu

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