#include <bits/stdc++.h>
using namespace std;
using cd = complex<double>;
const int INF = 1e9;
const long long mod = 1e9 + 7;
const long long p = 173;
const long long mod2 = 998244353;
const long long p2 = 137;
const double Pi = acos(-1);
void Fastio() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
}
signed main() {
  Fastio();
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    vector<pair<int, int> > Temp;
    for (int i = 1; i <= n; i++) {
      int temp;
      cin >> temp;
      Temp.emplace_back(temp, -i);
    }
    int Pointer = 0, ans = 0;
    sort(Temp.begin(), Temp.end());
    set<int> Group, Now;
    for (int i = 0; i < n; i++) {
      if (Temp[i].first != Temp[i - Now.size()].first) {
        for (auto x : Now) {
          Group.insert(x);
        }
        Now.clear();
      }
      while (Group.empty() == false && *Group.begin() < Temp[i].second) {
        Group.erase(Temp[Pointer].second);
        Pointer++;
      }
      Now.insert(Temp[i].second);
      ans = max(ans, (int)(Group.size() + Now.size()));
    }
    cout << n - ans << '\n';
  }
}
