An array is considered special if the parity of every pair of adjacent elements is different. In other words, one element in each pair must be even, and the other must be odd.
You are given an array of integers nums. Return true if nums is a special array, otherwise, return false.
Example 1:
Input: nums = [1]
Output: trueExplanation: There is only one element. So the answer is true.
Example 2:
Input: nums = [2,1,4]
Output: trueExplanation: There is only two pairs: (2,1) and (1,4), and both of them contain numbers with different parity. So the answer is true.
Example 3:
Input: nums = [4,3,1,6]
Output: falseExplanation: nums[1] and nums[2] are both odd. So the answer is false.
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 100Before attempting this problem, you should be comfortable with:
% 2 to determine if a number is even or oddn & 1 extracts the least significant bit to check parityAn array is special if every pair of adjacent elements has different parity (one is even, one is odd). To check this, we compare the parity of each element with its neighbor. Using the modulo operator, we can determine if a number is even (remainder 0 when divided by 2) or odd (remainder 1). If any two adjacent elements have the same parity, the array is not special.
1.2.false.true.Instead of using the modulo operator to check parity, we can use bitwise AND with 1. The least significant bit of a number determines its parity: if the bit is 1, the number is odd; if the bit is 0, the number is even. Bitwise operations are typically faster than modulo operations, making this approach slightly more efficient.
1.1.false.true.When iterating to compare adjacent elements, starting from index 0 instead of 1 can cause an out-of-bounds access when checking nums[i-1]. Always start from index 1 when comparing each element with its previous neighbor.
An array with only one element has no adjacent pairs to check, so it is trivially special. Forgetting this edge case can lead to incorrect logic or unnecessary iterations. The loop naturally handles this since iterating from 1 to len(nums) produces zero iterations when len(nums) == 1.
Sign in to join the discussion