LC3151. Special Array I
Solution
- Time Complexity: O(n)
- Space Complexity: O(1)
func isArraySpecial(nums []int) bool {
for i := 0; i < len(nums)-1; i++ {
if nums[i]%2 == nums[i+1]%2 {
return false
}
}
return true
}Explanation
The function isArraySpecial checks whether an array follows an alternating even-odd or odd-even pattern.
Approach
- Iterate through the array from index
0tolen(nums) - 2. - For each adjacent pair
(nums[i], nums[i+1]), check if both numbers have the same parity (i.e., both are even or both are odd). - If any two consecutive numbers have the same parity, return
false. - If no such pair exists, return
true.
Example Walkthrough
Example 1
nums := []int{1, 2, 3, 4, 5}
fmt.Println(isArraySpecial(nums)) // Output: true- 1 (odd) → 2 (even) → 3 (odd) → 4 (even) → 5 (odd)
- The array alternates correctly → returns
true.
Example 2
nums := []int{2, 4, 6, 8}
fmt.Println(isArraySpecial(nums)) // Output: false- 2 (even) → 4 (even)
- The first two numbers have the same parity → returns
false.
Complexity Analysis
- Time Complexity: O(n) → The function iterates through the array once.
- Space Complexity: O(1) → No extra space is used apart from the input.
This ensures an efficient solution with minimal overhead.

