#include <bits/stdc++.h>
using namespace std;
template <typename T>
string to_string(const vector<T>& vc, int w) {
  if (vc.empty()) return "";
  if (w + 1 == vc.size()) return to_string(vc[w]);
  return to_string(vc[w]) + "," + to_string(vc, w + 1);
}
template <typename T>
string to_string(const vector<T>& vc) {
  return "{" + to_string(vc, 0) + "}";
}
void debug_out() { cerr << endl; }
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
  cerr << " " << to_string(H);
  debug_out(T...);
}
class DebugStream {
} LOG;
template <typename T>
DebugStream& operator<<(DebugStream& s, const T&) {
  return s;
}
const int MAX = 200200;
int a[MAX];
int dp[MAX];
int cnt[MAX];
bool isLast[MAX], isFirst[MAX];
int b[MAX], pointer[MAX], q[MAX];
int main() {
  int T;
  scanf("%d", &T);
  for (int t = 0; t < int(T); t++) {
    int n;
    scanf("%d", &n);
    for (int i = 0; i < int(n); i++)
      scanf("%d", a + i), isLast[i] = false, isFirst[i] = false, b[i] = a[i];
    map<int, int> dic, last, first, invLast;
    for (int i = n - 1; i >= 0; i--) {
      if (dic[a[i]] == 0) {
        last[a[i]] = i;
        isLast[i] = true;
        invLast[a[i]] = i;
      }
      dic[a[i]]++;
      cnt[i] = dic[a[i]];
    }
    dic.clear();
    for (int i = 0; i < int(n); i++) {
      if (dic[a[i]] == 0) {
        first[a[i]] = i;
        isFirst[i] = true;
      }
      dic[a[i]]++;
    }
    map<int, int> nxt;
    sort(b, b + n);
    for (int i = 0; i < int(n - 1); i++) {
      nxt[b[i]] = b[i + 1];
    }
    nxt[b[n - 1]] = -1;
    dic.clear();
    for (int i = n - 1; i >= 0; i--) {
      if (dic.count(a[i])) {
        q[i] = dic[a[i]];
      } else {
        q[i] = -1;
      }
      dic[a[i]] = i;
      if (nxt[a[i]] != -1 && dic.count(nxt[a[i]]) == 1) {
        pointer[i] = dic[nxt[a[i]]];
      } else {
        pointer[i] = -1;
      }
    }
    int ans = 0;
    for (int i = n - 1; i >= 0; i--) {
      int j = i;
      dp[i] = cnt[j];
      j = invLast[a[i]];
      if (pointer[j] != -1) {
        if (isFirst[pointer[j]]) {
          dp[i] += dp[pointer[j]];
        } else {
          dp[i] += cnt[pointer[j]];
        }
      }
      ans = max(ans, dp[i]);
      42;
    }
    printf("%d\n", n - ans);
  }
}
