You are given ‘N’ distinct integers in the form of an array ‘ARR’. You need to find whether it is possible to sort the given array by choosing a continuous subarray and reversing that subarray. You have to return “true” if it is possible to sort the array after reversing the subarray. Otherwise, return “false”.
For example:Let ‘ARR’ be: [3, 2, 1]
We can pick the whole array as a subarray and reverse it to get the sorted array [1, 2, 3].
The first line of input contains an integer ‘T’, denoting the number of test cases.
The first line of each test case contains a single integer ‘N’, representing the size of the array.
The second line of each test case contains ‘N’ space-separated integers, representing the array ‘ARR’ elements.
Output Format :
For each test case, print ‘true’ if it is possible to sort the array after reversing the subarray, else print ‘false’.
Print output of each test case in a separate line.
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^6
1 <= ARR[i] <= 10^9
Time Limit: 1 sec
2
3
3 2 1
4
2 1 3 4
true
true
For test case 1:
We can pick the whole array as a subarray and reverse it to get the sorted array [1, 2, 3].
For test case 2:
We can pick the subarray from index 1 to 2, i.e., [2, 1], and reverse it to get a sorted array [1, 2, 3, 4].
2
2
1 2
4
3 1 2 4
true
false
Try to reverse all possible subarrays.
The basic idea is to reverse all the possible subarrays and check if the array is sorted or not. If the array is sorted, we simply return true. Else we again reverse that subarray to get back the original array and check for other subarrays possible.
Here is the algorithm:
O(N^3), where ‘N’ is the size of the array.
We iterate through each subarray that takes O(N ^ 2) of time and for each subarray, we reverse it and check whether the array is sorted or not which takes O(N) of time. Therefore, the overall time complexity will be O(N^3).
O(1).
We don't use any extra space. Therefore, the overall space complexity will be O(1).