Even-Odd Boundary Pairs — Problem Statement & Solution Guide
Problem Description
Given an array of integers, determine if every pair of elements equidistant from the ends of the array consists of exactly one even integer and exactly one odd integer. The array should have at least 3 elements.
Examples
Input
[4, 3, 2, 5, 6]
Output
false
Explanation: Step-by-step: Given the array [4, 3, 2, 5, 6], we first identify the equidistant pairs from the ends. The pairs are (4, 6), (3, 5), and (2, 2). Since the pair (2, 2) contains two even numbers, the condition is not met, and the output is false.
Input
[1, 3, 5, 7, 9]
Output
false
Explanation: Step-by-step: Given the array [1, 3, 5, 7, 9], we first identify the equidistant pairs from the ends. The pairs are (1, 9), (3, 7), and (5, 5). Since the pair (5, 5) contains two odd numbers, the condition is not met, and the output is false.
Constraints
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
Optimal Approach & Strategy
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.
Brute Force Approach
A naive approach would involve copying the array, reversing it, and checking if each element at index i in the original array has a different parity than the element at index i in the reversed array. This takes extra space and requires scanning the entire array twice.
Verified Code Solutions
function evenOddBoundaryPairs(arr) {
if (arr.length <= 2) return true;
for (let i = 0; i < Math.floor(arr.length / 2); i++) {
if ((arr[i] % 2 === 0 && arr[arr.length - 1 - i] % 2 === 0) || (arr[i] % 2 !== 0 && arr[arr.length - 1 - i] % 2 !== 0)) {
return false;
}
}
return true;
}class Solution {
public boolean solution(int[] nums) {
if (nums.length < 3) {
return false;
}
for (int i = 0; i < nums.length / 2; i++) {
if ((nums[i] % 2 == 0 && nums[nums.length - i - 1] % 2 != 0) || (nums[i] % 2 != 0 && nums[nums.length - i - 1] % 2 == 0)) {
continue;
} else {
return false;
}
}
return true;
}
}def solution(nums):
if len(nums) < 3:
return False
for i in range(len(nums) // 2):
if (nums[i] % 2 == 0 and nums[-i - 1] % 2 != 0) or (nums[i] % 2 != 0 and nums[-i - 1] % 2 == 0):
continue
else:
return False
return Truefunction evenOddBoundaryPairs(arr) {
if (arr.length <= 2) return true;
for (let i = 0; i < Math.floor(arr.length / 2); i++) {
if ((arr[i] % 2 === 0 && arr[arr.length - 1 - i] % 2 === 0) || (arr[i] % 2 !== 0 && arr[arr.length - 1 - i] % 2 !== 0)) {
return false;
}
}
return true;
}Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.