⚡Flashcard Drill➔
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.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

特殊数组 I

如果数组的每一对相邻元素都是两个 奇偶性不同 的数字,那么这个数组就是一个「特殊数组」。给你一个整数数组 nums,如果 nums 是一个特殊数组,返回 true,否则返回 false。约束:1 ≤ nums.length ≤ 100;1 ≤ nums[i] ≤ 100。

核心要点

  • 逐对检查奇偶性(标准解) :遍历所有相邻对,判断 nums[i] % 2 != nums[i-1] % 2 是否全部成立。
  • 位运算写法 : (nums[i] ^ nums[i-1]) &amp; 1 取异或的最低位,为 1 说明奇偶性不同。比取模稍快。
  • 为什么只比较相邻 :题目定义就是相邻对,无需检查非相邻元素。
  • 提前返回 :一旦发现奇偶性相同即可返回 False,无需扫描完。

常见陷阱

  • 用 nums[i] % 2 与 nums[i-1] % 2 比较时写成 == :题目要求奇偶性 不同 ,写成相等就正好反了。
  • 遍历范围写成 range(len(nums)) :会访问 nums[-1] 与 nums[0] 构成环状比较,题目要求的是线性相邻对,不构成环。
  • 长度 1 的数组 :没有相邻对,按定义是特殊数组,本解返回 True,正确。

参考实现

class Solution:
    def isArraySpecial(self, nums: list[int]) -> bool:
        for i in range(1, len(nums)):
            if (nums[i] & 1) == (nums[i - 1] & 1):   # 奇偶性相同 -> 不是特殊数组
                return False
        return True

# 一行写法:
# return all((a ^ b) & 1 for a, b in zip(nums, nums[1:]))