#include <bits/stdc++.h>
using namespace std;
long long add(long long a, long long b) {
  a %= 1000000007;
  b %= 1000000007;
  long long p = (a + b) % 1000000007;
  return (p + 1000000007) % 1000000007;
}
long long mul(long long a, long long b) {
  a %= 1000000007;
  b %= 1000000007;
  long long p = (a * b) % 1000000007;
  return (p + 1000000007) % 1000000007;
}
bool cmp(pair<long long, long long> a, pair<long long, long long> b) {
  if (a.first != b.first) return a.first < b.first;
  return a.second < b.second;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  long long t;
  long long a[200010];
  pair<long long, long long> p[200010];
  cin >> t;
  long long tot = t;
  long long tc = 1;
  while (t--) {
    long long i, j, n;
    cin >> n;
    map<long long, vector<long long> > m;
    map<long long, vector<long long> >::iterator it1, it2;
    for (i = 0; i < n; i++) {
      cin >> a[i];
      p[i] = {a[i], i};
      m[a[i]].push_back(i);
    }
    sort(p, p + n, cmp);
    long long ma = 0;
    for (it1 = m.begin(); it1 != m.end();) {
      long long cnt = 0;
      vector<long long> v = it1->second;
      ma = max(ma, (long long)v.size());
      it1++;
      it2 = it1;
      it1--;
      if (it2 == m.end()) break;
      vector<long long> v1 = it2->second;
      if (v1[0] < v[v.size() - 1]) {
        for (i = 0; i < v.size(); i++) {
          long long val = v1.end() - upper_bound(v1.begin(), v1.end(), v[i]);
          ma = max(ma, i + 1 + val);
        }
      }
      cnt += upper_bound(v.begin(), v.end(), v1[0]) - v.begin();
      cnt += v1.size();
      long long fl = 1;
      if (v1[0] < v[0]) fl = 0;
      if (fl) {
        v = v1;
        it2++;
        for (; it2 != m.end(); it2++) {
          v1 = it2->second;
          if (v1[0] < v[v.size() - 1]) {
            long long ele = v[v.size() - 1];
            cnt += v1.end() - upper_bound(v1.begin(), v1.end(), ele);
            ma = max(ma, cnt);
            break;
          }
          cnt += v1.size();
          v = v1;
        }
      }
      ma = max(ma, cnt);
      it2--;
      if (it1 != it2)
        it1 = it2;
      else
        it1++;
    }
    cout << n - ma << endl;
    tc++;
  }
  return 0;
}
