Special Array I
Problem
An array is special if the parity of every pair of adjacent elements is different — one of each pair must be even and the other odd. Given an integer array nums, return true if it is special, otherwise false. A single-element array is trivially special.
nums = [2, 1, 4]truedef is_array_special(nums):
# Compare each element with its predecessor.
for i in range(1, len(nums)):
# Same parity on both sides breaks the rule.
if nums[i] % 2 == nums[i - 1] % 2:
return False
# No adjacent pair shared parity -> special.
return True
function isArraySpecial(nums) {
// Compare each element with its predecessor.
for (let i = 1; i < nums.length; i++) {
// Same parity on both sides breaks the rule.
if (nums[i] % 2 === nums[i - 1] % 2) {
return false;
}
}
// No adjacent pair shared parity -> special.
return true;
}
boolean isArraySpecial(int[] nums) {
// Compare each element with its predecessor.
for (int i = 1; i < nums.length; i++) {
// Same parity on both sides breaks the rule.
if (nums[i] % 2 == nums[i - 1] % 2) {
return false;
}
}
// No adjacent pair shared parity -> special.
return true;
}
bool isArraySpecial(vector<int>& nums) {
// Compare each element with its predecessor.
for (int i = 1; i < (int)nums.size(); i++) {
// Same parity on both sides breaks the rule.
if (nums[i] % 2 == nums[i - 1] % 2) {
return false;
}
}
// No adjacent pair shared parity -> special.
return true;
}
Explanation
The condition is purely local: the array is special exactly when no two neighbours share the same parity. So we never need to look beyond a pair at a time.
We walk from index 1 to the end and compare each element nums[i] with the one just before it, nums[i-1]. Parity is captured by x % 2: 0 for even, 1 for odd.
If nums[i] % 2 == nums[i-1] % 2 the pair is either both even or both odd, which violates the rule, and we can return false immediately — there is no way a later fix could repair an already-broken pair.
If the loop finishes without finding such a pair, every adjacent pair alternated parity, so we return true. An array of length 1 has no pairs to check, so it is special by default.
Example: nums = [4,3,1,6]. Pair (4,3) alternates, but pair (3,1) is odd–odd, so the answer is false.