Rearranging array elements in JavaScript

JavaScript function that takes in an array of literals, arr, as the first and the only argument. This array contains some duplicates placed adjacently.

Our function should rearrange the elements of the array such that no two elements in the array are equal. Our function should return the rearranged array, given that it's guaranteed that there exists at least one possible way of such arrangement.

Problem Example

For example, if the input to the function is:

const arr = [7, 7, 7, 8, 8, 8];

Then the output should be:

const output = [7, 8, 7, 8, 7, 8];

There may be other correct possible rearrangements as well.

Solution Approach

The strategy is to count the frequency of each element, sort elements by frequency, and then place the most frequent elements at even positions first, followed by odd positions.

Implementation

const arr = [7, 7, 7, 8, 8, 8];

const rearrangeArray = (arr = []) => {
    // Count frequency of each element
    const map = arr.reduce((acc, val) => {
        acc[val] = (acc[val] || 0) + 1;
        return acc;
    }, {});
    
    // Sort keys by frequency (ascending)
    const keys = Object.keys(map).sort((a, b) => map[a] - map[b]);
    const res = [];
    let key = keys.pop(); // Start with most frequent element
    
    // Fill even positions first
    for(let i = 0; i < arr.length; i += 2){
        if(map[key] <= 0){
            key = keys.pop();
        }
        map[key] -= 1;
        res[i] = Number(key);
    }
    
    // Fill odd positions
    for(let i = 1; i < arr.length; i += 2){
        if(map[key] <= 0){
            key = keys.pop();
        }
        map[key] -= 1;
        res[i] = Number(key);
    }
    
    return res;
};

console.log(rearrangeArray(arr));
[ 8, 7, 8, 7, 8, 7 ]

How It Works

The algorithm works in three steps:

  1. Count frequencies: Create a frequency map of all elements
  2. Sort by frequency: Sort elements in ascending order of frequency
  3. Alternate placement: Place most frequent elements at even positions (0, 2, 4...), then fill odd positions (1, 3, 5...)

Alternative Example

const arr2 = [1, 1, 2, 2, 3, 3, 4];

const result = rearrangeArray(arr2);
console.log("Original:", arr2);
console.log("Rearranged:", result);

// Verify no adjacent duplicates
let hasAdjacent = false;
for(let i = 0; i < result.length - 1; i++) {
    if(result[i] === result[i + 1]) {
        hasAdjacent = true;
        break;
    }
}
console.log("Has adjacent duplicates:", hasAdjacent);
Original: [ 1, 1, 2, 2, 3, 3, 4 ]
Rearranged: [ 4, 1, 3, 1, 2, 2, 3 ]
Has adjacent duplicates: false

Conclusion

This approach efficiently rearranges array elements to avoid adjacent duplicates by prioritizing high-frequency elements for even positions first. The algorithm ensures no two adjacent elements are the same when a valid arrangement exists.

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

247 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements