#include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
using namespace std;
using ll = long long;
using db = long double;
using ii = pair<int, int>;
const int N = 1e6 + 5, LG = 19, MOD = 998244353;
const int SQ = 225;
int LessThan(vector<int>& v, int x) {
  return upper_bound(v.begin(), v.end(), x) - v.begin();
}
int MoreThan(vector<int>& v, int x) { return v.size() - LessThan(v, x); }
int32_t main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    map<int, vector<int>> mp;
    for (int i = 0, x; i < n; i++) {
      cin >> x;
      mp[x].push_back(i);
    }
    vector<vector<int>> vp;
    for (auto it : mp) {
      vp.push_back(it.second);
    }
    int mx = 0;
    for (int i = 0, j = 0; i < vp.size(); i = j) {
      int sum = vp[i].size();
      for (j = i + 1; j < vp.size() && vp[j][0] > vp[j - 1].back(); j++)
        sum += vp[j].size();
      if (i) sum += LessThan(vp[i - 1], vp[i][0]);
      if (j != vp.size()) sum += MoreThan(vp[j], vp[j - 1].back());
      mx = max(mx, sum);
    }
    cout << n - mx << '\n';
  }
  return 0;
}
