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:

  1. Initialize three lists: even_numbers, odd_numbers, and result.
  2. Iterate through the array using two pointers: i for the element and j for the index.
  3. For each element, check if the index j is even or odd:
    • If j is even, add the element to even_numbers. If it's odd, add it to odd_numbers.
  4. After iterating through the entire array, concatenate even_numbers and odd_numbers into result.

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

View on GeeksforGeeks
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);
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.