Special Array I - Problem

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.

Input & Output

Example 1 — Special Array
$ Input: nums = [1]
Output: true
💡 Note: Single element array is always special since there are no adjacent pairs to check.
Example 2 — Not Special Array
$ Input: nums = [2,1,4]
Output: true
💡 Note: Elements are 2(even), 1(odd), 4(even). Adjacent pairs (2,1) and (1,4) both have different parity, so the array is special.
Example 3 — Not Special Array
$ Input: nums = [4,3,1,6]
Output: false
💡 Note: Elements are 4(even), 3(odd), 1(odd), 6(even). Adjacent pair (3,1) both have odd parity, so array is not special.

Constraints

  • 1 ≤ nums.length ≤ 100
  • 1 ≤ nums[i] ≤ 100

Visualization

Tap to expand
Special Array I - Optimal Solution INPUT 1 index: 0 Input Values nums = [1] Array length: 1 Element 1 is ODD (1 % 2 = 1) ALGORITHM STEPS 1 Check Array Length If length <= 1, return true (No pairs to check) 2 Our Case: len = 1 Single element array has zero adjacent pairs 3 No Pairs to Validate Vacuously true: All 0 pairs are valid 4 Return Result Condition satisfied Return: true // Optimal check if (nums.length <= 1) return true; // O(1) time! FINAL RESULT true OK Why true? Single element array has no adjacent pairs to violate condition Output: true Key Insight: An array with 0 or 1 elements is always "special" because there are no adjacent pairs to check. The parity condition is vacuously true - all zero pairs satisfy the alternating parity requirement. Time Complexity: O(1) for this case, O(n) for general case | Space Complexity: O(1) TutorialsPoint - Special Array I | Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8
12.5K Views
Medium Frequency
~8 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen