#include <bits/stdc++.h>
using namespace std;
int n;
int v[200010];
int a[200010];
int c[200010];
int st[500010];
void update(int pos, int value) {
  for (st[pos += 200010] += value; pos > 1; pos >>= 1)
    st[pos >> 1] = max(st[pos], st[pos ^ 1]);
}
int query(int l, int r) {
  int ans = 0;
  r++;
  for (l += 200010, r += 200010; l < r; l >>= 1, r >>= 1) {
    if (l & 1) ans = max(ans, st[l++]);
    if (r & 1) ans = max(ans, st[--r]);
  }
  return ans;
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    cin >> n;
    for (int i = 0; i < n; ++i) cin >> v[i];
    auto ver = [](int k) {
      if (k == 1) return 0;
      memset(a, 0, sizeof a);
      memset(c, 0, sizeof c);
      memset(st, 0, sizeof st);
      for (int i = 0; i < k; ++i) {
        c[a[v[i]]]--;
        a[v[i]]++;
        c[a[v[i]]]++;
        update(v[i], 1);
      }
      int mx = query(0, 200010);
      if (c[mx] == 1) return 1;
      for (int i = k, ini = 0; i < n; ++i, ini++) {
        update(v[ini], -1);
        c[a[v[ini]]]--;
        a[v[ini]]--;
        c[a[v[ini]]]++;
        c[a[v[i]]]--;
        a[v[i]]++;
        c[a[v[i]]]++;
        update(v[i], 1);
        mx = query(0, 200010);
        if (c[mx] == 1) return 1;
      }
      return 0;
    };
    int a = 0, b = n;
    while (b - a > 1) {
      int mid = (a + b) / 2;
      if (ver(mid))
        b = mid;
      else
        a = mid;
    }
    if (ver(b))
      cout << b << "\n";
    else
      cout << "-1\n";
  }
  return 0;
}
