703246. Even and odd elements at even and odd positions
Easy
Even and odd elements at even and odd positions
Summary
Given an array of integers, we need to separate out all the even numbers that are present at even indices in the array. Similarly, we need to separate out all the odd numbers that are present at odd indices.
Tags: Arrays, Data Structures
Detailed Explanation
To solve this problem, we can iterate through the array and for each element, check if its index is even or odd. If it's an even index, we'll add the number to a separate list of even numbers. If it's an odd index, we'll add the number to a separate list of odd numbers.
Here's the step-by-step breakdown:
- Initialize three lists:
even_numbers,odd_numbers, andresult. - Iterate through the array using two pointers:
ifor the element andjfor the index. - For each element, check if the index
jis even or odd:- If
jis even, add the element toeven_numbers. If it's odd, add it toodd_numbers.
- If
- After iterating through the entire array, concatenate
even_numbersandodd_numbersintoresult.
Time complexity: O(n), where n is the length of the array. Space complexity: O(n/2) = O(n), since we're storing half the elements in each list.
Optimized Solutions
Java
public List<Integer> evenAndOdd(int[] arr) {
List<Integer> evenNumbers = new ArrayList<>();
List<Integer> oddNumbers = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
if (i % 2 == 0) { // even index
evenNumbers.add(arr[i]);
} else { // odd index
oddNumbers.add(arr[i]);
}
}
return List.of(evenNumbers, oddNumbers);
}