


Let’s say you have an array/list ‘ARR = [1,1,2,2]’.
Then a valid rearrangement can be [1,2,1,2] or [2,1,2,1] such that no two adjacent elements are equal. [2,1,1,2] is an invalid arrangement because two adjacent elements are equal.
The first line contains a single integer ‘T’ representing the number of test cases.
The first line of each test case contains a single integer ‘N’ representing the size of the array/list ‘ARR’.
The second line and the last line of input contain ‘N’ single space-separated integers representing the array/list elements.
For each test case, print the rearranged list/array. If it is a valid rearranged list then the code will output ‘True’ otherwise ‘False’.
1. You do not need to print anything; it has already been taken care of. Just implement the function.
2. You will need to return the rearranged array/list. If the rearranged list is a valid rearrangement then we will display ‘True’ as an output otherwise ‘False’ as output.
1 <= T <= 10
1 <= N <= 1000
1 <= ‘ARR[i]’ <= 10^3
Time Limit: 1sec
We can apply the algorithm as follows:-
We can put the highest frequency element first. It is a greedy approach. We use a set and put all elements and order by their frequencies. We take the highest frequency element and add it to the list. After we add, we decrease the frequency of the character and we temporarily move this element out of the set so that it is not picked next time. For example:- [1,1,2,2,2,3,3] If we do not remove 2 from the set after the first iteration it will again be the top element and then two consecutive elements will be the same in ‘ANS’.
Following is the algorithm for this approach:
We can put the highest frequency element first. It is a greedy approach. We use a priority queue or binary max-heap and put all elements and order by their frequencies. We take the highest frequency element and add it to the list. After we add, we decrease the frequency of the character and we temporarily move this character out of the priority queue so that it is not picked next time. For example:- [1,1,2,2,2,3,3] If we do not remove 2 from the priority queue after the first iteration it will again be the top element and then two consecutive elements will be the same in ‘ANS’.
Following is the algorithm for this approach: