#include <bits/stdc++.h>
using namespace std;
int tt;
void compress(vector<int> &a) {
  map<int, int> m;
  int cnt = 0;
  for (auto i : a) m[i] = 0;
  for (auto &i : m) i.second = cnt++;
  for (auto &i : a) i = m[i];
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cin >> tt;
  while (tt--) {
    int n;
    cin >> n;
    vector<int> v, dp, dp2;
    vector<vector<int>> pos;
    v.assign(n, 0);
    dp.assign(n, 1);
    dp2.assign(n, 1);
    pos.assign(n + 5, vector<int>());
    for (int i = 0; i < n; ++i) {
      cin >> v[i];
    }
    compress(v);
    for (int i = n - 1; i >= 0; --i) {
      pos[v[i]].push_back(i);
    }
    dp[0] = 1;
    for (int i = 1; i < n; ++i) {
      auto it1 =
          upper_bound(pos[v[i]].begin(), pos[v[i]].end(), i, greater<int>());
      int it2 = n + 1;
      if (v[i] - 1 >= 0) it2 = pos[v[i] - 1].front();
      if (it1 != pos[v[i]].end()) {
        dp[i] = max(dp[i], dp[*it1] + 1);
      }
      if (it2 < i)
        dp[i] = max(dp[i], dp2[it2] + 1);
      else {
        if (v[i] - 1 >= 0) {
          auto it3 = upper_bound(pos[v[i] - 1].begin(), pos[v[i] - 1].end(), i,
                                 greater<int>());
          if (it3 != pos[v[i] - 1].end()) {
            dp[i] = max(dp[i], int(pos[v[i] - 1].end() - it3) + 1);
          }
        }
      }
      if (i == pos[v[i]].front()) {
        dp2[i] = dp[pos[v[i]].back()] + (int)(pos[v[i]]).size() - 1;
      }
    }
    cout << n - *max_element(dp.begin(), dp.end()) << "\n";
  }
  return 0;
}
