You and Ram are friends who just started coding. You both took part in a coding competition. To win it, you have to solve a particular problem. You have given an array ‘ARR’ of integers. Find the minimum length of a subarray such that choosing this subarray will make the whole array sorted in ascending order.
Example :
Given ‘ARR’ : {1, 3, 2, 4, 5}
Selecting subarray {3, 2} and sorting it will make the whole array sorted.
Resultant ‘ARR’ : {1, 2, 3, 4, 5}
So, the minimum length will be 2.
The first line of input contains an integer ‘T’, 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 contains 'N' single space-separated integers representing the elements of the array.
Output Format :
For each test case, print a single integer representing the size of the subarray.
Print the 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 <= 2*10^3
1 <= ARR[i] <= 5*10^3
Time Limit : 1 sec
2
4
1 3 2 4
6
2 6 5 1 9 10
2
4
For first test case :
Choosing subarray {3, 2} and sorting it will result in a sorted array.
Resultant array : {1, 2, 3, 4}.
For second test case :
Choosing subarray {2, 6, 5, 1} and sorting it will result in a sorted array.
Resultant array : {1, 2, 5, 6, 9, 10}.
Think of sorting the array.
The basic idea is to create a copy of the given array and sort it. Then, by comparing the elements of both of the arrays, we can find the leftmost and rightmost mismatched elements.
Here is the algorithm :
O(N*log(N)), where ‘N’ is the size of the array.
We are creating a copy of our original array which takes O(N) time and then sorting it which takes O(N*log(N)) time. We also run a loop ‘N’ times to find mismatched elements which takes O(N) time. Therefore, the overall time complexity will be O(N*log(N)).
O(N), where ‘N’ is the size of the array.
We are using an extra space by making an array of size ‘N’. Therefore, the overall space complexity will be O(N).