#include <bits/stdc++.h>
using namespace std;
long long n;
long long x;
set<long long> others;
stack<long long> now;
long long ind = 0;
vector<pair<long long, long long> > massiv;
int main() {
  ios_base::sync_with_stdio(0);
  ;
  long long T;
  cin >> T;
  while (T--) {
    cin >> n;
    ind = 0;
    massiv.clear();
    for (long long i = 0; i < n; i++) {
      long long x;
      cin >> x;
      massiv.push_back(make_pair(x, -i));
    }
    sort((massiv).begin(), (massiv).end());
    long long maxx = 0;
    for (long long i = 0; i < n; i++) {
      if (massiv[i].first != massiv[i - (long long)now.size()].first) {
        while (!now.empty()) {
          others.insert(now.top());
          now.pop();
        }
      }
      while (!others.empty() && *(others.begin()) < massiv[i].second) {
        others.erase(massiv[ind].second);
        ind++;
      }
      now.push(massiv[i].second);
      maxx = max(maxx, (long long)now.size() + (long long)others.size());
    }
    cout << n - maxx << "\n";
    while (!now.empty()) now.pop();
    others.clear();
  }
  return 0;
}
