709904. Even Swap

Medium

Here is the Markdown blog post for the "Even Swap" problem:

Even Swap

Summary

The Even Swap problem requires you to sort an array of integers in such a way that all even numbers are swapped with their corresponding even numbers on the right side of the array. The key concept involved is array manipulation and sorting.

Detailed Explanation

To solve this problem, we can iterate through the array and keep track of the indices where even numbers are found. We then swap these even numbers with their corresponding even numbers to the right in a separate array. Once all swaps have been made, we concatenate the original array (excluding the even numbers) with the swapped even numbers to get the final sorted array.

Here is the step-by-step breakdown of the solution:

  1. Initialize two arrays: even and odd. even will store the indices of even numbers in the original array, while odd will store the odd numbers.
  2. Iterate through the original array:
    • For each number, check if it's even or odd.
    • If it's even, add its index to the even array.
    • If it's odd, add the number to the odd array.
  3. Swap the elements at indices in the even and odd arrays:
    • For each index in even, swap the element at that index with the element at the corresponding index from the end of the odd array (since we're working backwards).
  4. Concatenate the original array (excluding the even numbers) with the swapped even numbers to get the final sorted array.

Time complexity: O(n), where n is the length of the array. Space complexity: O(1), since we only use a constant amount of space to store the indices and arrays.

Optimized Solutions

Java

View on GeeksforGeeks
public int[] evenSwap(int[] arr) {
    int evenIndex = 0;
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] % 2 == 0) {
            evenIndex++;
        } else {
            // store odd numbers in a separate array
            arr[evenIndex++] = arr[i];
        }
    }

    int oddIndex = 0;
    for (int i = arr.length - 1; i >= 0; i--) {
        if (arr[i] % 2 != 0) {
            arr[i] = arr[--oddIndex];
        }
    }

    return arr;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.