#include <bits/stdc++.h>
using namespace std;
int n, m;
int a[500500];
int b[500500];
set<int> have;
int badBefore[500500];
int badAfter[500500];
void init() {
  for (int i = 0; i <= n; i++) badBefore[i] = 500500, badAfter[i] = -1;
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    cin >> n;
    have.clear();
    for (int i = 0; i < n; i++) {
      cin >> a[i];
      have.insert(a[i]);
    }
    m = 0;
    for (set<int>::iterator it = have.begin(); it != have.end(); it++)
      b[m++] = *it;
    init();
    have.clear();
    for (int i = 0; i < n; i++) {
      set<int>::iterator it = have.upper_bound(a[i]);
      if (it != have.end()) badBefore[a[i]] = min(badBefore[a[i]], *it);
      have.insert(a[i]);
    }
    have.clear();
    for (int i = n - 1; i >= 0; i--) {
      set<int>::iterator it = have.lower_bound(a[i]);
      if (it != have.begin()) {
        it--;
        badAfter[a[i]] = max(badAfter[a[i]], *it);
      }
      have.insert(a[i]);
    }
    int j = 0, ans = 0;
    for (int i = 0; i < m; i++) {
      while (j + 1 < m) {
        if (badBefore[b[i]] <= b[j + 1]) break;
        if (badAfter[b[j + 1]] >= b[i]) break;
        j++;
      }
      ans = max(ans, j - i + 1);
    }
    cout << have.size() - ans << endl;
  }
  return 0;
}
