#include <bits/stdc++.h>
using namespace std;
int v[200000 + 5];
void umax(int &a, int b) { a = max(a, b); }
struct sgtree {
  sgtree() {}
  pair<int, int> yy[4 * 200000 + 5];
  void build(int p, pair<int, int> itv) {
    if (itv.first == itv.second) {
      yy[p].first = itv.first;
      return;
    }
    int mid = (itv.first + itv.second) / 2;
    build(p * 2, {itv.first, mid});
    build(p * 2 + 1, {mid + 1, itv.second});
  }
  void update(int p, pair<int, int> itv, int ok, int val) {
    if (ok < itv.first || ok > itv.second) return;
    if (itv.first == itv.second) {
      yy[p].second += val;
      return;
    }
    int mid = (itv.first + itv.second) / 2;
    update(p * 2, {itv.first, mid}, ok, val);
    update(p * 2 + 1, {mid + 1, itv.second}, ok, val);
    if (yy[p * 2].second > yy[p * 2 + 1].second)
      yy[p] = yy[p * 2];
    else
      yy[p] = yy[p * 2 + 1];
  }
  void preupdate(int ok, int val) { update(1, {1, 200000}, ok, val); }
  pair<int, int> q_query;
  void query(int p, pair<int, int> itv, pair<int, int> ok) {
    if (ok.second < itv.first || itv.second < ok.first) return;
    if (itv.first >= ok.first && itv.second <= ok.second) {
      if (yy[p].second > q_query.second) q_query = yy[p];
      return;
    }
    int mid = (itv.first + itv.second) / 2;
    query(p * 2, {itv.first, mid}, ok);
    query(p * 2 + 1, {mid + 1, itv.second}, ok);
  }
  pair<int, int> prequery(pair<int, int> ok) {
    q_query = {0, -1};
    if (ok.first <= ok.second) query(1, {1, 200000}, ok);
    return q_query;
  }
};
sgtree aint;
bool can(int n, int l) {
  int i, j, z, flag = 0;
  for (i = 0; i < l; i++) aint.preupdate(v[i], 1);
  for (i = l; i <= n && !flag; i++) {
    pair<int, int> best = aint.prequery({1, 200000});
    aint.preupdate(best.first, -best.second);
    pair<int, int> sbest = aint.prequery({1, 200000});
    aint.preupdate(best.first, best.second);
    if (best.second > sbest.second) flag = 1;
    if (i < n) {
      aint.preupdate(v[i - l], -1);
      aint.preupdate(v[i], 1);
    }
  }
  for (i = 0; i < n; i++) {
    pair<int, int> cur = aint.prequery({v[i], v[i]});
    aint.preupdate(cur.first, -cur.second);
  }
  return flag;
}
void solver() {
  int n;
  cin >> n;
  int i, j, z;
  for (i = 0; i < n; i++) cin >> v[i];
  int pas;
  for (z = n + 1, pas = (1 << 18); pas > 0; pas /= 2)
    if (z - pas >= 2 && can(n, z - pas)) z -= pas;
  if (z == n + 1)
    cout << -1 << '\n';
  else
    cout << z << '\n';
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  aint.build(1, {1, 200000});
  int t;
  cin >> t;
  while (t--) solver();
  return 0;
}
