NeetCode #62LC-3151EasyArrays & Hashing
← Back to All Problems

#62 · #3151 · Special Array I(特殊数组 I)

📌 Problem Statement & Constraints

An array is special if the parity of every adjacent pair of elements differs. Given an integer array nums, return true if it is special. Constraints: 1 <= nums.length <= 100, 1 <= nums[i] <= 100.

💡 Core Algorithmic Approaches

  1. The condition is local, so a single pass checking adjacent pairs suffices.
  2. Two elements have different parity exactly when nums[i] % 2 != nums[i + 1] % 2.
  3. Equivalently, (nums[i] + nums[i + 1]) % 2 == 1: an odd sum means one is even and the other is odd.
  4. An array of length 1 is trivially special, since there are no pairs -- the loop body never runs.

💻 Benchmark Python3 Implementation

class Solution:
    def isArraySpecial(self, nums: List[int]) -> bool:
        for i in range(len(nums) - 1):
            if (nums[i] + nums[i + 1]) % 2 == 0:   # same parity -> not special
                return False
        return True

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass over adjacent pairs.
💾 Space Complexity
O(1): no extra state.

⚠️ Interview Pitfalls & Follow-ups

  • Comparing nums[i] != nums[i+1]: the requirement is about parity, not equality. [2, 4] has distinct values but the same parity, so it is not special.
  • Comparing nums[i] % 2 == nums[i+1] % 2 as the success condition: the sign is inverted; equal parity means failure.
  • Handling a single-element array as a special case: the loop already returns True for it, which is correct.