easyArraysPattern: Two Pointers
Even-Odd Boundary Pairs Solution
Problem Statement
You are given an array of integers. Your task is to determine if every pair of elements equidistant from the ends of the array consists of exactly one even integer and exactly one odd integer. You should compare the first element with the last element, the second element with the second-to-last element, and so on, moving towards the center. If the array has an odd length, the single element remaining in the middle does not have to be paired and can be ignored.
Examples
Example 1:
Input:nums = [2, 3, 8, 5]
Output:true
Explanation: The outer pairs are (2, 5) and (3, 8). The first pair contains an even and an odd number. The second pair contains an odd and an even number. Since all pairs satisfy the condition, the output is true.
Example 2:
Input:nums = [4, 6, 7, 2]
Output:false
Explanation: The first pair of elements to check from the boundaries is (4, 2). Since both 4 and 2 are even numbers, this pair violates the condition, so the output is false.
Constraints
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
Time: O(N) Space: O(1)
Using the two-pointer technique, we place one pointer at the start and another at the end of the array. In a single pass, we check if the elements at these pointers have different parity (one even, one odd). We increment the left pointer and decrement the right pointer, immediately returning false if any pair violates the condition.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
No solution code is currently loaded.
Complete this code in the workspace editor.
