Deque sorting

5

6 votes
Sorting, Algorithms, Advanced Sorting
Problem

You are given an array A of N distinct integers, your task is to sort the given array using the below operation.

  •  Choose any element, take it out of the array without changing the order of other elements, and put it back either in front or back.

Your task is to print the minimum number of operations to achieve this.

Input format

  • The first line contains an integer denoting the number of test cases T
  • The first line of each test case contains an integer N denoting the number of elements in array A.
  • The second line of each test case contains N space-separated integers of array A.

Output format

Print T lines. For each test case:

  • Print a single line indicating the minimum number of operations to be performed.

Constraints

1T20000

1N200000

1Ai109i[1,N]

All Ai are distinct.

The sum of N over all test cases does not exceed 200000.

Sample Input
1
5
7 3 1 5 4
Sample Output
3
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

[7,3,1,5,4] in the beginning, for optimal conversion:

  • Remove 5 and insert in the end  [7,3,1,4,5]
  • Remove 7 and insert in the end  [3,1,4,5,7]
  • Remove 1 and insert in the beginning [1,3,4,5,7]

There is no way which involves lesser than three steps.

Editor Image

?