Special Array I (LeetCode 3151): Solution and Explanation
An array is special when the parity of its numbers alternates: every adjacent pair has one odd and one even value. Return whether nums is special.
Intuition
Only parity matters, so paint every number in one of two colors: odd or even. The question becomes whether the colors alternate along the array.
Colors alternate exactly when every link between neighbours joins two different colors. One link with the same color on both ends is enough to say no.
So walk the links from left to right and stop at the first bad one. An array with a single number has no links at all and is special by default.
Approach: Adjacent parity check
- For each
ifrom 1 ton - 1, comparenums[i] % 2withnums[i - 1] % 2. - If they are equal, return
falseimmediately. - If the loop finishes, return
true.
Step-by-step example
nums = [1]
- There is one number, so the loop over pairs never runs.
- No pair can break the pattern. Return true.
- For comparison, [4,3,1,6] fails at the pair (3,1): both are odd, so the answer there is false.
Code: Python, Java, C++
1class Solution:
2 def isArraySpecial(self, nums: List[int]) -> bool:
3 for i in range(1, len(nums)):
4 if nums[i] % 2 == nums[i - 1] % 2:
5 return False
6 return True1class Solution {
2 public boolean isArraySpecial(int[] nums) {
3 for (int i = 1; i < nums.length; i++) {
4 if (nums[i] % 2 == nums[i - 1] % 2) {
5 return false;
6 }
7 }
8 return true;
9 }
10}1class Solution {
2public:
3 bool isArraySpecial(vector<int>& nums) {
4 for (int i = 1; i < (int)nums.size(); i++) {
5 if (nums[i] % 2 == nums[i - 1] % 2) {
6 return false;
7 }
8 }
9 return true;
10 }
11};Time and space complexity
O(n)
Each of the n - 1 adjacent pairs is checked at most once, and the loop stops at the first failure.
O(1)
Only the loop index is stored.
Other approaches
XOR of the low bits (time O(n), space O(1))
Two numbers have different parity exactly when (a ^ b) & 1 is 1. Same pass, using a bit test instead of the modulo.
Compare against the first parity (time O(n), space O(1))
In a special array, nums[i] % 2 equals (nums[0] + i) % 2 for every i. Checking that formula gives the same answer without looking at neighbours.
Common mistakes
- Returning false for a single-element array. With no adjacent pairs the condition holds trivially.
- Checking only that odd and even numbers appear equally often. [1,3,2,4] has two of each but is not special.
- Starting the loop at 0 and reading nums[-1], which wraps around in Python and is out of bounds elsewhere.
Frequently asked questions
Why is a one-element array special?
The rule is about adjacent pairs, and a single element has none. Nothing can violate the rule, so the answer is true.
Do I need to look at the whole array?
Only when it is special. The first pair with the same parity decides the answer, so you can return false right there.
Does the first element have to be odd?
No. Either parity can start the array, as long as the parities alternate after it.