
Ninja is given a few numbers, and he is being asked to rearrange the numbers so that every second element is greater than its left and right element.
Suppose the given array is [1, 2, 3, 4, 5] then the rearranged array can be [1, 3, 2, 5, 4].
The first line of input contains a single integer T, representing the number of test cases.
The first line of each test case contains ‘N’, denoting the number of elements in the array.
The second line of each test case contains the array elements.
Output Format :
The first and only line of each test case in the output contains 1 if the array satisfies the conditions mentioned.
Note:
If the array returned is the rearranged array following all the conditions, then it will print 1 else it will print 0.
You are not required to print the expected output; it has already been taken care of. Just implement the function.
1 <= T <= 10
1 <= N <= 10^4
0 <= array[i] <= 10^5
Time limit: 1 sec
2
7
1 2 3 4 5 6 7
4
8 2 4 6
1
1
In the first test case, [1, 3, 2, 5, 4, 7, 6] is one possible answer. The reason is every second element of the array is greater than its left and right element. So on returning this 1 is the output.
In the second test case, [2, 8, 4, 6] is one possible answer. The reason is every second element of the array is greater than its left and right element. So on returning this 1 is the output.
2
6
9 7 1 2 9 6
3
3 2 1
1
1
Can you sort the array?
We will sort the array. Then we take an auxiliary array and fill it with the elements of the sorted array starting from both the ends in an alternate order.
The steps are as follows:
O(NLogN), where ‘N’ is the number of elements in the array.
As we are sorting the whole array, it takes N*LogN time. Hence, the overall complexity is O(NLogN).
O(N), where ‘N’ is the number of elements in the array
As we require an auxiliary array, hence the overall complexity is O(N).