#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
int v[200200];
int freq[200200];
set<int> invfreq[200200];
set<int> bird;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) cin >> v[i];
    int ans = INF;
    int lo = 2;
    int hi = n;
    while (lo <= hi) {
      bird.clear();
      int mid = (lo + hi) / 2;
      memset(freq, 0, sizeof(freq));
      for (int i = 0; i < n; i++) {
        invfreq[i].clear();
      }
      int p = 0;
      int q = 0;
      while (q - p + 1 <= mid) {
        int x = v[q];
        freq[x]++;
        q++;
      }
      q--;
      for (int i = 0; i < n; i++) {
        int x = v[i];
        int f = freq[x];
        invfreq[f].insert(x);
        bird.insert(f);
      }
      int flag = 0;
      int freqmax = *bird.rbegin();
      if (invfreq[freqmax].size() == 1) {
        flag = 1;
        goto fim;
      }
      while (q < n - 1) {
        q++;
        int x1 = v[p];
        int x2 = v[q];
        int f1 = freq[x1];
        int f2 = freq[x2];
        invfreq[f1].erase(x1);
        if (invfreq[f1].size() == 0) bird.erase(f1);
        freq[x1]--;
        f1 = freq[x1];
        if (freq[x1] != 0) invfreq[f1].insert(x1);
        if (invfreq[f1].size() == 1) bird.insert(f1);
        p++;
        invfreq[f2].erase(x2);
        if (invfreq[f2].size() == 0) bird.erase(f2);
        freq[x2]++;
        f2 = freq[x2];
        invfreq[f2].insert(x2);
        if (invfreq[f2].size() == 1) bird.insert(f2);
        freqmax = *bird.rbegin();
        if (invfreq[freqmax].size() == 1) {
          flag = 1;
          break;
        }
      }
    fim:
      if (flag) {
        hi = mid - 1;
        ans = min(ans, mid);
      } else {
        lo = mid + 1;
      }
    }
    if (ans >= INF) ans = -1;
    cout << ans << endl;
  }
}
