Special Array I Problem
#3151
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3151.
An array is considered special if the parity of every pair of adjacent elements is different. In other words, one element in each pair must be even, and the other must be odd.
You are given an array of integers nums. Return true if nums is a special array, otherwise, return false.
Example 1:
Input: nums = [1]
Output: true
Explanation:
There is only one element. So the answer is true.
Example 2:
Input: nums = [2,1,4]
Output: true
Explanation:
There is only two pairs: (2,1) and (1,4), and both of them contain numbers with different parity. So the answer is true.
Example 3:
Input: nums = [4,3,1,6]
Output: false
Explanation:
nums[1] and nums[2] are both odd. So the answer is false.
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 100
Solution
Approach: Single Pass
Compare each pair of neighbors. If two adjacent numbers have the same parity the array is not special; if no such pair exists it is.
Complexity: O(n) time and O(1) extra space.
class Solution:
def isArraySpecial(self, nums: List[int]) -> bool:
return all(a % 2 != b % 2 for a, b in zip(nums, nums[1:]))