Special Array I — Easy Problem & Solution

An array is special when every pair of adjacent elements has different parity — one odd and one even. Return whether nums is special.

  • Difficulty: Easy
  • Topics: Arrays
  • Asked at: Amazon, Google, Cognizant
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

An array is special when every pair of adjacent elements has different parity — one odd and one even.

Return whether nums is special. An array of one element is special.

Example 1

Input: nums = [1]
Output: true
Explanation: A single element has no adjacent pair.

Example 2

Input: nums = [2,1,4]
Output: true
Explanation: even, odd, even.

Example 3

Input: nums = [4,3,1,6]
Output: false
Explanation: 3 and 1 are both odd.

Constraints

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100

How to solve Special Array I

Walk the array comparing each element's parity with its predecessor's; a single match makes the array non-special.

Approach

  1. For each index from 1 onward, compare nums[i] % 2 with nums[i-1] % 2.
  2. Return false on the first equal pair, true otherwise.

Why it works

Comparing parities rather than the values themselves is the whole point — two different numbers of the same parity still break the rule. Using (a ^ b) & 1 is the same test written with bit operations, which is what the follow-up version of this problem needs when the queries come in ranges.

Complexity

  • Time — O(n)
  • Space — O(1)

Pitfalls

  • The rule is about parity, not about the values differing.
  • A one-element array is special by definition.
  • Only adjacent pairs matter, not all pairs.

Reference solution

Python

from typing import List

def isArraySpecial(nums: List[int]) -> bool:
    return all(nums[i] % 2 != nums[i - 1] % 2 for i in range(1, len(nums)))

JavaScript

var isArraySpecial = function(nums) {
    for (var i = 1; i < nums.length; i++) {
        if ((nums[i] % 2) === (nums[i - 1] % 2)) return false;
    }
    return true;
};

Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 667 arrays problems · the whole catalogue