Two-Pointer Approach

In this approach, we use two pointers, one starting from the beginning (left) and one starting from the end (right) of the array. We alternately pick elements from the end and the beginning and place them in the result array until we traverse the entire array.

Example: This function takes an input array, uses two pointers to pick elements alternately from the end and the beginning, and stores them in the result array. It then prints the rearranged array.

JavaScript
function rearrangeAlternately(arr) {
    let n = arr.length;
    let result = new Array(n);
    let left = 0, right = n - 1;
    let index = 0;

    while (left <= right) {
        if (index % 2 === 0) {
            result[index++] = arr[right--];
        } else {
            result[index++] = arr[left++];
        }
    }

    return result;
}

let inputArray1 = [1, 2, 3, 4, 5, 6, 7];
let rearrangedArray1 = rearrangeAlternately(inputArray1);
console.log(rearrangedArray1);

let inputArray2 = [12, 15, 67, 81, 90, 92];
let rearrangedArray2 = rearrangeAlternately(inputArray2);
console.log(rearrangedArray2);

Output
[
  7, 1, 6, 2,
  5, 3, 4
]
[ 92, 12, 90, 15, 81, 67 ]

Time Complexity: O(n)

Space Complexity: O(n)



JavaScript Program to Rearrange Array Alternately

Rearranging an array alternately means, If we have a sorted array then we have to rearrange the array such that the first largest element should come at index-0(0-based indexing), first smallest element should come at index-1, similarly, second largest element should come at index-3 and second smallest element should come at index-4 and so on. Below are the examples:

Example:

Input: arr1  = {1, 2, 3, 4, 5, 6, 7}
Output: {7, 1, 6, 2, 5, 3, 4}
Input: arr2 = {12, 15, 67, 81, 90, 92}
Output: {92, 12, 90, 15, 81, 67}

Similar Reads

Approach 1: Iterative Flag-Based

In this approach, The arrayAlternately function rearranges elements of an array alternately, starting with the last element followed by the first, in a concise manner using a loop and a flag to toggle between elements....

Approach 2: Using Copy of Array

In this approach, we creates a sorted copy of the input array using slice() and sort(). Then, it iterates through the original array, alternately appending elements from the sorted copy either from the end or the beginning, based on the iteration count....

Approach 3: Two-Pointer Approach

In this approach, we use two pointers, one starting from the beginning (left) and one starting from the end (right) of the array. We alternately pick elements from the end and the beginning and place them in the result array until we traverse the entire array....