702920. Even Greater than Odd

Easy

Even Greater than Odd

Summary

Given an array of integers, rearrange its elements such that even positioned elements are greater than odd positioned elements. This problem involves sorting and manipulation of arrays, making it a classic algorithmic challenge.

Detailed Explanation

To solve this problem, we can use a simple two-pointer approach. We maintain two pointers, i and j, starting from the beginning of the array. The i pointer points to even-indexed elements, while the j pointer points to odd-indexed elements.

Here's the step-by-step breakdown:

  1. Initialize i and j to 0.
  2. While i < n-1 (where n is the length of the array), do:
    • If arr[i] <= arr[j], increment i. This ensures that even-indexed elements are greater than or equal to odd-indexed elements at this point.
    • Otherwise, swap arr[i] and arr[j]. This brings an element from the odd position to an even position, making it possible for the next iteration.
  3. Repeat step 2 until i >= n-1.
  4. Return the rearranged array.

The time complexity of this algorithm is O(n), where n is the length of the input array. The space complexity is O(1) since we only use a constant amount of space to store the pointers and temporary variables.

Optimized Solutions

Java

View on GeeksforGeeks
public static int[] evenGreater(int[] arr) {
    int i = 0, j = 1;
    while (i < arr.length - 1) {
        if (arr[i] <= arr[j]) {
            i++;
        } else {
            swap(arr, i, j);
        }
        j = i + 2;
    }
    return arr;
}

private static void swap(int[] arr, int i, int j) {
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.