Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created February 1, 2025 22:10
Show Gist options
  • Save Ifihan/a2c24a0be6f52493f03c594ce7274ac6 to your computer and use it in GitHub Desktop.
Save Ifihan/a2c24a0be6f52493f03c594ce7274ac6 to your computer and use it in GitHub Desktop.
Special Array I

Question

Approach

1

My first approach was to first check if the length of the array nums was 1. If it was, I will return True. Next, I set up a loop to iterate over every element in the array. Normally, I would expect to compare each pair of adjacent elements—comparing nums[i] with nums[i+1] to ensure that one is even and the other is odd. However, the code I wrote doesn’t actually compare adjacent pairs. Instead, within the loop, I use a condition that checks (nums[i] % 2 == 0 or nums[i] % 2 != 0) for each element. I realized that this condition is always true for any integer because every number is either even or odd. Since I repeat this check twice with an and between them, the overall condition remains always true.

Implementation

class Solution:
    def isArraySpecial(self, nums: List[int]) -> bool:
        if len(nums) == 1:
            return True

        for i in range(len(nums)):
            if (nums[i] % 2 == 0 or nums[i] % 2 != 0) and (nums[i] % 2 == 0 or nums[i] % 2 != 0):
                return False
            else:
                return True

Complexities

  • Time: O(n)
  • Space: O(1)

2

My second approach was more inclusive. Instead of the unnecessary complex conditional, I iterate through the array from the first element up to the second-to-last element. For each index i, I compare the parity of nums[i] and nums[i + 1] by checking the remainder when divided by 2. If the remainder of both elements is the same, it means both numbers are either even or odd, which violates the requirement that adjacent elements have different parity. In that case, I return False. If I finish the loop without finding any adjacent pair with the same parity, I then return True.

Implementation

class Solution:
    def isArraySpecial(self, nums: List[int]) -> bool:
        if len(nums) == 1:
            return True

        for i in range(len(nums) - 1):
            if nums[i] % 2 == nums[i + 1] % 2:
                return False
        return True

Complexities

  • Time: O(n)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment