You have been given an array/list ‘ARR’ of integers consisting of ‘N' integers. You need to rearrange ‘ARR’ so that no two adjacent elements are equal. You may return any valid rearrangement and it is guaranteed the answer exists.
Example :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.
Output Format :
For each test case, print the rearranged list/array. If it is a valid rearranged list then the code will output ‘True’ otherwise ‘False’.
Note :
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
2
4
1 3 3 4
4
1 1 2 2
True
True
Test case 1:
One of the possible rearrangements is [3,1,4,3].
Therefore the answer is ‘True’. But you have to return a rearranged array.
Test case 2:
One of the possible rearrangements is [1,2,1,2].
Therefore the answer is ‘True’.
2
4
1 2 3 4
7
1 1 2 2 3 3 4
True
True
Naively iterate over all permutations of the array.
We can apply the algorithm as follows:-
O(‘N!'), where ‘N’ denotes the size of the array/list.
For an array/list of size ‘N’ there are ‘N!’ permutations.
O(1).
As we are using constant extra space.