Special Array I (LeetCode 3151): Solution and Explanation

Easy
Array

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

  1. For each i from 1 to n - 1, compare nums[i] % 2 with nums[i - 1] % 2.
  2. If they are equal, return false immediately.
  3. If the loop finishes, return true.

Step-by-step example

nums = [1]
  1. There is one number, so the loop over pairs never runs.
  2. No pair can break the pattern. Return true.
  3. 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 True
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each of the n - 1 adjacent pairs is checked at most once, and the loop stops at the first failure.

Space

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.