#include <bits/stdc++.h>
#pragma GCC optimize("O3")
using namespace std;
using ll = long long;
using P = pair<ll, ll>;
template <class T>
using V = vector<T>;
const ll inf = (1e18);
const ll mod = 1000000007;
const vector<int> dy = {-1, 0, 1, 0}, dx = {0, -1, 0, 1};
ll GCD(ll a, ll b) { return b ? GCD(b, a % b) : a; }
ll LCM(ll c, ll d) { return c / GCD(c, d) * d; }
struct __INIT {
  __INIT() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(20);
  }
} __init;
template <class T>
bool chmax(T &a, const T &b) {
  if (a < b) {
    a = b;
    return 1;
  }
  return 0;
}
template <class T>
bool chmin(T &a, const T &b) {
  if (a > b) {
    a = b;
    return 1;
  }
  return 0;
}
template <class T>
void debag(const vector<T> &a) {
  cerr << "debag :";
  for (auto v : a) cerr << v << " ";
  cerr << "\n";
}
template <class T>
void print(const vector<T> &a) {
  for (auto v : a) cout << v << " ";
  cout << "\n";
}
void solve() {
  int n;
  cin >> n;
  map<int, int> mp;
  V<int> a(n);
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    mp[a[i]];
  }
  int num = 0;
  for (auto &p : mp) {
    p.second = num++;
  }
  for (int i = 0; i < n; i++) {
    a[i] = mp[a[i]];
  }
  V<V<int>> idx(n);
  for (int i = 0; i < n; i++) {
    idx[a[i]].emplace_back(i);
  }
  V<int> cur(n, -1);
  V<V<int>> dp(n, V<int>(3, 0));
  for (int i = 0; i < n; i++) {
    while (cur[a[i]] + 1 < idx[a[i]].size() && idx[a[i]][cur[a[i]] + 1] < i)
      cur[a[i]]++;
    if (a[i])
      while (cur[a[i] - 1] + 1 < idx[a[i] - 1].size() &&
             idx[a[i] - 1][cur[a[i] - 1] + 1] < i)
        cur[a[i] - 1]++;
    if (cur[a[i]] >= 0) {
      int id = idx[a[i]][cur[a[i]]];
      for (int j = 0; j < 3; j++) chmax(dp[i][j], dp[id][j] + 1);
    } else {
      for (int j = 0; j < 3; j++) dp[i][j] = 1;
    }
    if (a[i] > 0 && cur[a[i] - 1] >= 0) {
      int id = idx[a[i] - 1][cur[a[i] - 1]];
      if (cur[a[i]] == -1) chmax(dp[i][1], dp[id][0] + 1);
      if (cur[a[i]] == -1 && cur[a[i] - 1] + 1 == idx[a[i] - 1].size())
        chmax(dp[i][1], dp[id][1] + 1);
      chmax(dp[i][2], dp[id][0] + 1);
      if (cur[a[i] - 1] + 1 == idx[a[i] - 1].size())
        chmax(dp[i][2], dp[id][1] + 1);
    }
  }
  int ans = 0;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < 3; j++) chmax(ans, dp[i][j]);
  cout << n - ans << "\n";
}
int main() {
  int t = 1;
  cin >> t;
  while (t--) solve();
}
