


If ‘N’ = 5, ‘ARR’ = {1, 2, 4, 5, 3}
You can sort the given arrangement in two steps.
In the first step select the student with roll number 4 (ARR[2]) and place him at the end, the arrangement now becomes: {1, 2, 3, 5, 3, 4}. In the second step select the student with roll number 5 (ARR[3]) and place him at the end, resulting in the arrangement: {1, 2, 3, 4, 5} which is in sorted order.
It is not possible to sort the given arrangement in less than two steps, therefore we will print 2.
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 students in the class.
The second line of each test case contains N integers ‘ARR’, denoting the initial arrangement of the students, each array element denotes the roll number of one of the students.
For each test case, print the minimum steps required to rearrange the students.
Output for each test case will be printed in a separate line.
You are not required to print anything; it has already been taken care of. Just implement the function.
1 ≤ T ≤ 10
1 ≤ N ≤ 20000
1 ≤ ARR[i] ≤ N
Time limit: 1 sec
There is a big observation that we need to preserve the order of some terms, and we can rearrange all other terms, the optimal rearrangement will result in finally sorting the array so we don’t have to take that into account while calculating the answer.
As our answer directly depends on the terms that we have to preserve (these terms will not be rearranged), there is another clever observation that these terms should be increasing and should be one unit greater than the previous term. This is because after rearranging all other terms in between, then these preserved terms will come adjacent to each other, and according to the task we had to sort the array in increasing order of the roll numbers.
To do this, we simply need to find the longest subsequence that has the current term one unit greater than the previous one, there are multiple ways to do this, one of the easiest ways to tackle it is by using a hash-map. We can store the maximum length of the subsequence ending with ARR[i] in the hash-map, later when we encounter the ARR[i] + 1 term, we can use the previously stored information to build our answer further.
The steps are as follows :