#3151

Special Array I

Easy
ArrayArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution is similar to the brute force approach but emphasizes the fact that we can check for parity in a single pass without needing to store any additional information.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a variable to track the expected parity (even or odd) based on the first element.
  2. 2Step 2: Iterate through the array starting from the second element.
  3. 3Step 3: For each element, check if its parity matches the expected parity. If it does, return false.
  4. 4Step 4: Update the expected parity for the next iteration.
  5. 5Step 5: If the loop completes without returning false, return true.
solution.py9 lines
1# Full working Python code
2
3def is_special_array(nums):
4    expected_parity = nums[0] % 2
5    for i in range(1, len(nums)):
6        if (nums[i] % 2) == expected_parity:
7            return False
8        expected_parity = 1 - expected_parity  # Toggle parity
9    return True

Complexity note: This complexity is O(n) because we still make a single pass through the array. Space complexity is O(1) since no additional data structures are used.

  • 1Adjacent elements must have different parities.
  • 2The parity can be toggled to simplify checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.