Matching odd even indices with values in JavaScript

We are required to write a JavaScript function that takes in an array of numbers. The array given as an input to the function have two special properties ?

  • The length of the array will always be an even number.

  • The number of even numbers and the number of odd numbers in the array will always be equal (i.e., both being equal to the half of the length of array)

The function should shuffle the elements of the array such that all the even values occupy even indices and all the odd values occupy odd indices.

Note that there may be more than one correct solution to this problem, we are required to find any one of them.

How the Algorithm Works

The solution uses a two-pointer approach:

  • Even pointer starts at index 0 and moves by 2 (0, 2, 4, ...)

  • Odd pointer starts at index 1 and moves by 2 (1, 3, 5, ...)

  • When an odd number is found at an even index AND an even number is found at an odd index, they are swapped

  • Otherwise, the pointers advance to find misplaced elements

Example

Following is the code ?

const arr = [1, 2, 3, 4, 5, 6];

const arrangeToIndices = (arr = []) => {
    let [even, odd] = [0, 1];
    
    while (even < arr.length && odd < arr.length) {
        if (arr[even] % 2 === 1 && arr[odd] % 2 === 0) {
            // Swap misplaced elements
            [arr[even], arr[odd]] = [arr[odd], arr[even]];
            [even, odd] = [even + 2, odd + 2];
        } else {
            // Move pointers if elements are correctly placed
            if (0 === arr[even] % 2) {
                even += 2;
            }
            if (1 === arr[odd] % 2) {
                odd += 2;
            }
        }
    }
    return arr;
};

console.log("Original array:", arr);
console.log("Rearranged array:", arrangeToIndices([...arr]));
Original array: [1, 2, 3, 4, 5, 6]
Rearranged array: [2, 1, 4, 3, 6, 5]

Step-by-Step Execution

Let's trace through the algorithm with array [1, 2, 3, 4, 5, 6]:

const traceAlgorithm = (arr) => {
    console.log("Initial array:", arr);
    let [even, odd] = [0, 1];
    let step = 1;
    
    while (even < arr.length && odd < arr.length) {
        console.log(`Step ${step}: even=${even}, odd=${odd}`);
        console.log(`arr[${even}]=${arr[even]} (${arr[even] % 2 === 0 ? 'even' : 'odd'}), arr[${odd}]=${arr[odd]} (${arr[odd] % 2 === 0 ? 'even' : 'odd'})`);
        
        if (arr[even] % 2 === 1 && arr[odd] % 2 === 0) {
            console.log(`Swapping ${arr[even]} and ${arr[odd]}`);
            [arr[even], arr[odd]] = [arr[odd], arr[even]];
            [even, odd] = [even + 2, odd + 2];
        } else {
            if (0 === arr[even] % 2) {
                console.log(`Even number ${arr[even]} correctly placed at even index ${even}`);
                even += 2;
            }
            if (1 === arr[odd] % 2) {
                console.log(`Odd number ${arr[odd]} correctly placed at odd index ${odd}`);
                odd += 2;
            }
        }
        
        console.log("Array after step:", arr);
        step++;
    }
    
    return arr;
};

traceAlgorithm([1, 2, 3, 4, 5, 6]);
Initial array: [1, 2, 3, 4, 5, 6]
Step 1: even=0, odd=1
arr[0]=1 (odd), arr[1]=2 (even)
Swapping 1 and 2
Array after step: [2, 1, 3, 4, 5, 6]
Step 2: even=2, odd=3
arr[2]=3 (odd), arr[3]=4 (even)
Swapping 3 and 4
Array after step: [2, 1, 4, 3, 5, 6]
Step 3: even=4, odd=5
arr[4]=5 (odd), arr[5]=6 (even)
Swapping 5 and 6
Array after step: [2, 1, 4, 3, 6, 5]

Testing with Different Arrays

const testArrays = [
    [2, 1, 4, 3, 6, 5],  // Already arranged
    [8, 7, 6, 5, 4, 3],  // Reverse pattern
    [1, 3, 2, 4, 5, 6]   // Mixed arrangement
];

testArrays.forEach((testArr, index) => {
    const original = [...testArr];
    const result = arrangeToIndices(testArr);
    console.log(`Test ${index + 1}:`);
    console.log(`Original: [${original.join(', ')}]`);
    console.log(`Result:   [${result.join(', ')}]`);
    console.log('');
});
Test 1:
Original: [2, 1, 4, 3, 6, 5]
Result:   [2, 1, 4, 3, 6, 5]

Test 2:
Original: [8, 7, 6, 5, 4, 3]
Result:   [8, 7, 6, 5, 4, 3]

Test 3:
Original: [1, 3, 2, 4, 5, 6]
Result:   [2, 3, 4, 1, 6, 5]

Key Points

  • Time Complexity: O(n) - each element is visited at most once

  • Space Complexity: O(1) - only uses two pointer variables

  • In-place: The algorithm modifies the original array without using extra space

  • Multiple solutions: Different valid arrangements are possible for the same input

Conclusion

This algorithm efficiently rearranges an array so that even numbers occupy even indices and odd numbers occupy odd indices using a two-pointer swapping technique. The solution works in linear time and requires no additional space.

Updated on: 2026-03-15T23:19:00+05:30

268 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements