#include <bits/stdc++.h>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template <class T, class V>
ostream& operator<<(ostream& s, pair<T, V> a) {
  s << a.first << ' ' << a.second;
  return s;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  long long int T = 1;
  cin >> T;
  for (long long int qq = 1; qq <= T; qq++) {
    long long int n;
    cin >> n;
    map<long long int, vector<long long int> > mp;
    for (int i = 0; i < n; i++) {
      long long int x;
      cin >> x;
      mp[x].push_back(i);
    }
    if (mp.size() == 1) {
      cout << 0 << endl;
      continue;
    }
    auto it = mp.rbegin();
    auto it2 = mp.rbegin();
    long long int ans = n - 1, last = it->second[0], l = 0, r = 0;
    long long int cnt = it->second.size();
    it++;
    for (int i = 0; i < n - 1; i++) {
      while (it != mp.rend() && it->second[l] < last) {
        l++;
        cnt++;
        if (it->second.size() == l) last = it->second[0], it++, l = 0;
      }
      ans = min(ans, n - cnt + i);
      r++;
      if (last == it2->second[r - 1]) {
        if (it2->second.size() == r) {
          it2++, r = 0;
          while (l < it->second.size()) l++, cnt++;
          it++;
          l = 0;
        }
        last = it2->second[r];
      } else if (it2->second.size() == r)
        it2++, r = 0;
    }
    cout << ans << endl;
  }
  return 0;
}
