# 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}
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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:

1. 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.
2. 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 }
3. 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.
4. 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 { ` ` `  `    ``// 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 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); ` `    ``} ` `} `

Output:

```1 3 1 2 1 3 2 1
```

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

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.