#include <bits/stdc++.h>
using namespace std;
int n;
pair<int, int> a[300009];
pair<int, int> b[300009];
int d[300009];
int e[300009];
int x[300009];
int xl;
int main() {
  int t, tv = 0;
  int i, j, k, l;
  scanf("%d", &t);
  while (t--) {
    scanf("%d", &n);
    xl = 0;
    for (i = 0; i < n; i++) {
      scanf("%d", &a[i].first);
      a[i].first--;
      x[xl++] = a[i].first;
      a[i].second = i;
    }
    sort(x, x + xl);
    xl = unique(x, x + xl) - x;
    for (i = 0; i < n; i++) {
      a[i].first = lower_bound(x, x + xl, a[i].first) - x;
    }
    sort(a, a + n);
    i = 0;
    for (k = 0; k < xl; k++) {
      b[k].first = i;
      for (; i < n; i++)
        if (a[i].first != k) break;
      b[k].second = i;
    }
    for (i = 0; i < xl; i++) {
      d[i] = 0;
      e[i] = xl - 1;
    }
    for (i = 1; i < xl; i++) {
      d[i] = d[i - 1];
      if (a[b[i].first].second < a[b[i - 1].second - 1].second) {
        d[i] = i;
      }
    }
    for (i = xl - 2; i >= 0; i--) {
      e[i] = e[i + 1];
      if (a[b[i].second - 1].second > a[b[i + 1].first].second) {
        e[i] = i;
      }
    }
    int res = xl + 1;
    for (i = j = 0; i < xl && j < xl;) {
      for (; i < xl; i++)
        if (d[i] == i) break;
      for (; j < xl; j++) {
        if (j < i) continue;
        if (e[j] == j) break;
      }
      if (i == xl) break;
      int cur = i + (xl - 1 - j);
      if (res > cur) res = cur;
      i++;
    }
    if (res > xl) res = 0;
    printf("%d\n", res);
  }
}
