Problem Description
Given an array of integers, determine if it is a special array. An array is special if the parity (even/odd) of every adjacent pair of elements is different. Return true if the array is special; otherwise, return false.
Key Insights
- A single element array is inherently special.
- Only adjacent pairs need to be checked for differing parity.
- Use the modulo operator (%) to determine if a number is odd (num % 2 != 0) or even (num % 2 == 0).
Space and Time Complexity
Time Complexity: O(n), where n is the number of elements in the array. Space Complexity: O(1), as only a constant amount of extra memory is used.
Solution
The solution involves iterating through the array and checking the parity of each pair of adjacent elements using the modulo operator. If the parity of any adjacent pair is the same (both even or both odd), the function returns false immediately. If no pairs with matching parity are found, the function returns true. The approach uses a simple loop, guaranteeing an efficient O(n) time complexity, and only a constant amount of additional memory, yielding O(1) space complexity.