Rearrange numbers in an array such that no two adjacent numbers are same
Given an array of integers. The task is to rearrange elements of the array such that no two adjacent elements in the array are same.
Examples:
Input: arr[] = {1, 1, 1, 2, 2, 2} Output: {2, 1, 2, 1, 2, 1} Input: arr[] = {1, 1, 1, 1, 2, 2, 3, 3} Output: {1, 3, 1, 3, 2, 1, 2, 1}
The idea is to put the highest frequency element first (a greedy approach). We use a priority queue (Or Binary Max Heap) and put all elements and ordered by their frequencies (highest frequency element at the root). We then one by one take the highest frequency element from the heap and add it to result. After we add, we decrease the frequency of the element and temporarily move this element out of priority queue so that it is not picked next time.
We have to follow the step to solve this problem, they are:

Build a Priority_queue or max_heap, pq that stores elements and their frequencies.
…… Priority_queue or max_heap is built on the bases of the frequency of elements.  Create a temporary Key that will be used as the previously visited element (the previous element in the resultant array. Initialize it { num = 1, freq = 1 }
 While pq is not empty.
 Pop an element and add it to the result.
 Decrease frequency of the popped element by ‘1’.
 Push the previous element back into the priority_queue if it’s frequency > ‘0’.
 Make the current element as the previous element for the next iteration.
 If the length of resultant string and original are not equal, print “not possible”. Else print result.
Below is the implementation of the above approach:
// Java Program to rearrange numbers in an Array // such that no two numbers are adjacent import java.util.Comparator; import java.util.PriorityQueue; // Comparator class to sort in descending order class KeyComparator implements Comparator<Key> { // Overriding compare()method of Comparator public int compare(Key k1, Key k2) { if (k1.freq < k2.freq) return 1 ; else if (k1.freq > k2.freq) return  1 ; return 0 ; } } // Object of num and its freq class Key { int freq; // store frequency of character int num; Key( int freq, int num) { this .freq = freq; this .num = num; } } public class GFG { // Function to rearrange numbers in array such // that no two adjacent numbers are same static void rearrangeArray( int [] arr) { int n = arr.length; // Store frequencies of all elements // of the array int [] count = new int [ 10000 ]; int visited[] = new int [ 10000 ]; for ( int i = 0 ; i < n; i++) count[arr[i]]++; // Insert all characters with their frequencies // into a priority_queue PriorityQueue<Key> pq = new PriorityQueue<>( new KeyComparator()); // Adding high freq elements in descending order for ( int i = 0 ; i < n; i++) { int val = arr[i]; if (count[val] > 0 && visited[val] != 1 ) pq.add( new Key(count[val], val)); visited[val] = 1 ; } // 'result[]' that will store resultant value int result[] = new int [n]; // work as the previous visited element // initial previous element will be ( '1' and // it's frequency will also be '1' ) Key prev = new Key( 1 ,  1 ); // Traverse queue int l = 0 ; while (pq.size() != 0 ) { // pop top element from queue and add it // to result Key k = pq.peek(); pq.poll(); result[l] = k.num; // If frequency of previous element is less // than zero that means it is useless, we // need not to push it if (prev.freq > 0 ) pq.add(prev); // make current element as the previous // decrease frequency by 'one' (k.freq); prev = k; l++; } // If length of the resultant array and original // array is not same then the array is not valid if (n != result.length) { System.out.println( " Not valid Array " ); } // Otherwise Print the result array else { for ( int i : result) { System.out.print(i + " " ); } } } // Driver Code public static void main(String args[]) { int arr[] = new int [] { 1 , 1 , 1 , 1 , 2 , 2 , 3 , 3 }; rearrangeArray(arr); } } 
1 3 1 2 1 3 2 1
Recommended Posts:
 Rearrange positive and negative numbers in O(n) time and O(1) extra space
 Lambda expression in Python to rearrange positive and negative numbers
 Rearrange positive and negative numbers using inbuilt sort function
 Print all distinct integers that can be formed by K numbers from a given array of N numbers
 Arrange first N natural numbers such that absolute difference between all adjacent elements > 1
 Rearrange characters in a string such that no two adjacent are same
 Rearrange characters in a string such that no two adjacent are same using hashing
 Absolute Difference between the Sum of NonPrime numbers and Prime numbers of an Array
 Minimum number greater than the maximum of array which cannot be formed using the numbers in the array
 Numbers less than N which are product of exactly two distinct prime numbers
 GCD of more than two (or array) numbers
 Given an array and three numbers, maximize (x * a[i]) + (y * a[j]) + (z * a[k])
 Average numbers in array
 XOR of all Prime numbers in an Array
 Sum of all prime numbers in an Array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.