Alternating Parity Check
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
A single element vacuously satisfies the alternating rule.
The sequence alternates even, odd, even, odd.
Two odd numbers appear consecutively.
Algorithm Flow
Solution Approach
This problem asks whether the parity (evenness or oddness) of the numbers alternates all the way through the list. The list passes only if every pair of neighbors has different parity; a single break makes the whole answer false.
The key is that we only need to compare adjacent numbers — no sorting or complex calculations are required. We check each pair and, if two neighbors share the same parity, we return false immediately.
Here is the implementation:
We first handle the easy cases: an empty list or a single element always passes, because there are no neighbors to violate the pattern. Then we loop over consecutive pairs and compare their remainders modulo 2. If two neighbors have the same remainder, the alternation has broken and we return false.
Let us trace nums = [2, 5, 6, 3]. Comparing 2 and 5 (even vs odd) passes, 5 and 6 (odd vs even) passes, and 6 and 3 (even vs odd) passes, so the function returns true. For nums = [1, 3, 5], the pair 1 and 3 are both odd, so it returns false right away.
Notice that using % 2 works for negative numbers too, since the parity of a negative integer is well defined by its remainder.
The time complexity is O(n) because we scan the list once, and the space complexity is O(1).
Best Answers
class Solution {
public boolean alternating_parity_check(int[] nums) {
if (nums.length <= 1) {
return true;
}
for (int i = 0; i < nums.length - 1; i++) {
if ((nums[i] % 2) == (nums[i+1] % 2)) {
return false;
}
}
return true;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
