#include <bits/stdc++.h>
using namespace std;
template <typename T>
void deb(initializer_list<T> l) {
  for (auto& e : l) cout << e << ' ';
  cout << endl;
}
int search(vector<int>& a, int val) {
  int n = a.size();
  int lo = 0;
  int hi = n - 1;
  while (lo < hi) {
    int mid = lo + (hi - lo) / 2;
    if (a[mid] > val)
      hi = mid;
    else
      lo = mid + 1;
  }
  return a[lo] > val ? a[lo] : -1;
}
vector<vector<int>> dp;
int f(int i, int j, vector<int>& a, vector<vector<int>>& idx, int num) {
  int& ret = dp[i][j];
  if (ret != -1) return ret;
  ret = 0;
  if (j) {
    if (idx[a[i]][0] != i) {
      int nextIdx = search(idx[a[i]], i);
      if (nextIdx != -1) ret = f(nextIdx, 1, a, idx, num);
      ++ret;
      return ret;
    }
    ret = idx[a[i]].size();
    if (a[i] == num - 1) return ret;
    int nextIdx = search(idx[a[i] + 1], idx[a[i]].back());
    if (nextIdx != -1) ret += f(nextIdx, 1, a, idx, num);
    return ret;
  }
  int nextIdx = search(idx[a[i]], i);
  if (nextIdx != -1) ret = f(nextIdx, 0, a, idx, num);
  if (a[i] == num - 1) {
    ++ret;
    return ret;
  }
  nextIdx = search(idx[a[i] + 1], i);
  if (nextIdx != -1) ret = max(ret, f(nextIdx, 1, a, idx, num));
  ++ret;
  return ret;
}
void solve() {
  int n;
  cin >> n;
  vector<int> a(n);
  set<int> s;
  for (auto& e : a) {
    cin >> e;
    s.insert(e);
  }
  map<int, int> m;
  int num = 0;
  for (auto& e : s) m[e] = num++;
  vector<vector<int>> idx(num);
  for (int i = 0; i < n; ++i) {
    a[i] = m[a[i]];
    idx[a[i]].push_back(i);
  }
  dp.assign(n, vector<int>(2, -1));
  int maxLen = 1;
  for (int i = 0; i < n; ++i) {
    maxLen = max(maxLen, f(i, 0, a, idx, num));
  }
  cout << n - maxLen << '\n';
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  int t = 1;
  cin >> t;
  while (t--) solve();
  return 0;
}
