You are given an array containing ‘N’ integers. You need to find if it’s possible to convert the given sequence into an Arithmetic Progression by rearranging the array elements, print “true” if it is possible, else print “false”.
For Example :If ‘N’ = 5, ‘ARR’ = {2, 4, 10, 8, 6}
You can rearrange ‘ARR’ to now become {2, 4, 6, 8, 10} this is an arithmetic progression. Therefore we will print “true”.
The first line contains a single integer ‘T’ denoting the number of test cases, then each test case follows:
The first line of each test case contains a single integer ‘N’, denoting the number of elements in the array.
The second line of each test case contains N integers ‘ARR’, denoting the array elements.
Output Format :
For each test case, print “true” if the given array can be rearranged to form an A.P., else print “false”.
Output for each test case will be printed in a separate line.
Note :
You are not required to print anything; it has already been taken care of. Just implement the function.
1 ≤ T ≤ 10
3 ≤ N ≤ 5000
-10^9 ≤ ARR[i] ≤ 10^9
Time limit: 1 sec
2
5
2 4 10 8 6
4
2 4 6 9
true
false
For test case 1 :
We will print “true” because:
Then given array can be rearranged as {2, 4, 6, 8, 10} which is an AP.
For test case 2 :
We will print “false” because:
There is no way to rearrange the input array so that it forms an AP.
2
5
2 4 8 16 32
6
1 1 1 1 1 1
false
true
Try to sort the array and then check for AP sequence.
An arithmetic sequence is either a non-increasing or a non-decreasing sequence, depending on the value of difference b/w two consecutive elements of AP. This means that simply sorting and then checking for AP sequence is sufficient. To check for the AP sequence in a sorted array, simply check the difference between adjacent elements is equal.
The steps are as follows :
O( N * log ( N ) ), where N denotes the size of the array.
Sorting an array of size N takes time equal to N*log(N).
Hence the time complexity is O( N * log ( N ) ).
O( 1 )
No auxiliary space is used.
Hence the space complexity is O( 1 ).