Special Array I

easy array parity simulation

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.

Inputnums = [2, 1, 4]
Outputtrue
Pairs (2,1) and (1,4) each mix an even and an odd number, so every adjacent pair has different parity.

def 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;
}
Time: O(n) Space: O(1)