We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Special Array I

Number: 3429

Difficulty: Easy

Paid? No

Companies: Google, Microsoft, National Payments Corporation of India


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.


Code Solutions

# Function to check if the array is special
def is_special_array(nums):
    # Iterate through the array, checking each adjacent pair
    for i in range(len(nums) - 1):
        # If both elements share the same parity, return False
        if nums[i] % 2 == nums[i + 1] % 2:
            return False
    # Return True if all adjacent pairs have differing parity
    return True

# Example usage:
result = is_special_array([2, 1, 4])
print(result)  # Expected Output: True
← Back to All Questions