Special Array I
Easy · Arrays & Hashing · Explanation and code example
Bitwise Comparison
How it works
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.
Steps
- Iterate through the array starting from index
1. - For each index, extract the least significant bit of the current and previous elements using bitwise AND with
1. - If both bits are the same, the elements have the same parity, so return
false. - If all adjacent pairs have different parities, return
true.
Complexity
- Time complexity:
O(n) - Space complexity:
O(1)
Things to watch for
Off-by-One Errors in Loop Bounds
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.
Forgetting Single-Element Arrays
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.
Python code example
from typing import List
class Solution:
def isArraySpecial(self, nums: List[int]) -> bool:
for i in range(1, len(nums)):
if nums[i - 1] & 1 == nums[i] & 1:
return False
return True
C++ code example
class Solution {
public:
bool isArraySpecial(vector<int>& nums) {
for (int i = 1; i < nums.size(); i++) {
if ((nums[i - 1] & 1) == (nums[i] & 1)) {
return false;
}
}
return true;
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.