Back to blog
Feb 14, 2024
3 min read

Special Array I

Determine if an array is special by checking if every pair of adjacent elements has different parity.

Difficulty: Easy | Acceptance: 81.60% | Paid: No Topics: Array

An array is considered special if every pair of adjacent elements of the array have different parity.

Return true if the array is special, otherwise return false.

Examples

Input: nums = [1]
Output: true
Explanation:
There is only one element, so the array is special.
Input: nums = [2, 1, 4]
Output: true
Explanation:
All adjacent pairs have different parity:
- (2, 1): 2 is even, 1 is odd.
- (1, 4): 1 is odd, 4 is even.
Input: nums = [4, 3, 1, 6]
Output: false
Explanation:
The pair (1, 6) has the same parity (both are odd), so the array is not special.

Constraints

1 <= nums.length <= 100
1 <= nums[i] <= 100

Iterative Check

Intuition We can iterate through the array once, comparing the parity of each element with the next one. If any adjacent pair has the same parity, the array is not special.

Steps

  • Iterate from the first element to the second-to-last element.
  • For each element at index i, check if nums[i] % 2 equals nums[i + 1] % 2.
  • If they are equal, return false.
  • If the loop completes without finding any equal parity pairs, return true.
python
class Solution:
    def isArraySpecial(self, nums: list[int]) -&gt; bool:
        for i in range(len(nums) - 1):
            if (nums[i] % 2) == (nums[i + 1] % 2):
                return False
        return True

Complexity

  • Time: O(n)
  • Space: O(1)
  • Notes: This is the most efficient approach with a single pass.

Functional Approach

Intuition We can utilize built-in functional programming constructs to check if the condition holds for all adjacent pairs simultaneously.

Steps

  • Create a sequence or stream of adjacent pairs.
  • Check if all pairs satisfy the condition that their parities are different.
  • Return the result of the check.
python
class Solution:
    def isArraySpecial(self, nums: list[int]) -&gt; bool:
        return all((a % 2) != (b % 2) for a, b in zip(nums, nums[1:]))

Complexity

  • Time: O(n)
  • Space: O(1) or O(n) depending on language implementation of intermediate streams/iterators.
  • Notes: More concise but may have slight overhead compared to the iterative loop.