//белый снег
//белый porshe
//белый trash
//в бонге воск
#include <iostream>
#include <locale>
#include <string>
#include <iomanip>
#include <string.h>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <vector>
#include <stdlib.h>
#include <clocale>
#include <algorithm>
#include <iterator>
#include <list>
#include <set>
#include <cstddef>
#include <cstdio>
#include <stdio.h>
#include <map>
#include <cmath>
#include <functional>
#include <stack>
#include <type_traits>
#include <queue>
#include <memory>
#include <memory.h>
#include <time.h>
#include <ctime>
#pragma warning(disable:4996)
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4")
using namespace std;
#define Kirja_ES ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
#define pb push_back
#define pf push_front
#define irt insert
#define ll long long
#define ull unsigned long long
#define str string
#define vi vector<int>
#define vll vector<ll>
#define si set<int>
#define sll set<ll>
#define msi multiset<int>
#define msll multiset<ll>
#define pii pair<int, int>
#define pll pair<ll, ll>
#define left false
#define right true
void solve()
{
	int n;
	cin >> n;
	map<int, si> in;
	int k = n, numb = -1;
	si in1;
	for (int i = 0; i < n; ++i)
	{
		int h;
		cin >> h;
		in[h].irt(i);
		in1.irt(h);
	}
	for (auto& it : in1)
	{
		in[it].irt(-1);
		in[it].irt(n);
		int pred = 0;
		int razn = 0;
		for (auto& it1 : in[it])
		{
			if (it1 != -1)
			{
				razn = max(razn, it1 - pred);
			}
			pred = it1;
		}
		if (razn <= k)
		{
			k = razn;
			numb = it;
		}
	}
		for (int i = 1; i <= n; ++i)
	{
		if (i < k)
			cout << "-1 ";
		else
			cout << numb << " ";
	}
	cout << "\n";
	return;
}
signed main()
{
	Kirja_ES;
	int t;
	cin >> t;
	while (t--)
		solve();
}


#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
	int t;
	cin >> t;
	for (int i = 0; i < t; i++)
	{
		int n;
		cin >> n;
		vector<int> numbs(n);
		map<int, int> numb_length;
		map<int, int> numb_index;
		map<int, int> checked;
		map<int, int> result;
		for (int j = 0; j < n; j++)
		{
			cin >> numbs[j];
			if (numb_length.count(numbs[j]) != 0)
			{
				numb_length[numbs[j]] = max(j - numb_index[numbs[j]], numb_length[numbs[j]]);
			}
			else
			{
				numb_length[numbs[j]] = j + 1;
			}
			numb_index[numbs[j]] = j;
		}
		for (int j = n - 1; j >= 0; j--)
		{
			if (checked.count(numbs[j]) == 0)
				numb_length[numbs[j]] = max(numb_length[numbs[j]], n - j);
			checked[numbs[j]] = 1;
		}
		for (auto& length : numb_length)
		{
			if (result.count(length.second) == 0)
			{
				result[length.second] = length.first;
			}
		}
		int u = 1;
		int wat_want_print = -1;
		for (const auto& res_k : result)
		{
			while (u < res_k.first )
			{
				cout << wat_want_print << " ";
				u++;
			}
			if(wat_want_print == -1)
				wat_want_print = res_k.second;
			else
			{
				wat_want_print = min(wat_want_print, res_k.second);
			}
		}
		for (u; u < n + 1; u++)
		{
			cout << wat_want_print << " ";
		}
		cout << '\n';
	}
}


#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
	int t;
	cin >> t;
	for (int i = 0; i < t; i++)
	{
		int n;
		cin >> n;
		vector<int> numbs(n);
		map<int, int> numb_length;
		map<int, int> numb_index;
		map<int, int> checked;
		for (int j = 0; j < n; j++)
		{
			cin >> numbs[j];
			if (numb_length.count(numbs[j]) != 0)
			{
				numb_length[numbs[j]] = max(j - numb_index[numbs[j]], numb_length[numbs[j]]);
			}
			else
			{
				numb_length[numbs[j]] = j+1;
			}
			numb_index[numbs[j]] = j;
		}
		for (int j = n - 1; j >= 0; j--)
		{
			if (checked.count(numbs[j]) == 0)
				numb_length[numbs[j]] = max(numb_length[numbs[j]], n - j);
			checked[numbs[j]] = 1;
		}
		for (int k = 1; k < n + 1; k++)
		{
			bool print = true;
			for (const auto& length : numb_length)
			{
				if (length.second <= k)
				{
					cout << length.first << " ";
					print = false;
					break;
				}
			}
			if (print)
			{
				cout << "-1 ";
			}
		}
		cout << '\n';
	}
}


#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#include<set>
#include<map>
using namespace std;
#define MOD 1000000007
#define ll long long
#define pii pair<int, int>
#define pil pair<int, ll>
#define pli pair<ll, int>
#define pll pair<ll, ll>

int ans[300001];
vector<int> v[300001];

int f(int n, int k)
{
	int temp = max(v[k][0] + 1, n - v[k].back());
	for (int i = 1; i < v[k].size(); i++)
		temp = max(temp, v[k][i] - v[k][i - 1]);
	return temp;
}

int main()
{
	int t, n, temp;
	scanf("%d", &t);
	for (; t > 0; t--)
	{
		scanf("%d", &n);
		for (int i = 0; i < n; i++)
		{
			scanf("%d", &temp);
			v[temp].push_back(i);
		}
		memset(ans, -1, sizeof(ans));
		for (int i = 1; i <= n; i++)
		{
			if (!v[i].empty())
			{
				temp = f(n, i);
				v[i].clear();
				for (int j = temp; j <= n; j++)
					if (ans[j] == -1)
						ans[j] = i;
					else
						break;
			}
		}
		for (int i = 1; i <= n; i++)
			printf("%d ", ans[i]);
		printf("\n");
	}
	return 0;
}


#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#include<set>
#include<map>
using namespace std;
#define MOD 1000000007
#define ll long long
#define pii pair<int, int>
#define pil pair<int, ll>
#define pli pair<ll, int>
#define pll pair<ll, ll>

int ans[300001];
vector<int> v[300001];

int f(int n, int k)
{
	int temp = max(v[k][0], n - v[k].back());
	for (int i = 1; i < v[k].size(); i++)
		temp = max(temp, v[k][i] - v[k][i - 1]);
	return temp;
}

int main()
{
	int t, n, temp;
	scanf("%d", &t);
	for (; t > 0; t--)
	{
		scanf("%d", &n);
		for (int i = 0; i < n; i++)
		{
			scanf("%d", &temp);
			v[temp].push_back(i);
		}
		memset(ans, -1, sizeof(ans));
		for (int i = 1; i <= n; i++)
		{
			if (!v[i].empty())
			{
				temp = f(n, i);
				v[i].clear();
				for (int j = temp; j <= n; j++)
					if (ans[j] == -1)
						ans[j] = i;
					else
						break;
			}
		}
		for (int i = 1; i <= n; i++)
			printf("%d ", ans[i]);
		printf("\n");
	}
	return 0;
}


#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <functional>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <set>
using namespace std;

#define fastio ios_base::sync_with_stdio(false); cin.tie(NULL)
#define ll long long
#define ii pair < int, int >
#define Iii pair < int, ii >
#define LL pair < ll, ll >
#define INF 1000000007
#define LINF 1000000000000000007

#define data int
#define p_q priority_queue < data >
#define np_q priority_queue < data, vector < data >, greater < data > >

int arr[300005];
int ans[300005];

int main()
{
	int t;
	scanf("%d", &t);

	while (t--)
	{
		int n;
		scanf("%d", &n);

		vector < vector < int > > v;
		v.resize(n + 1);
		for (int i = 1; i <= n; i++)
			v[i].push_back(0);

		for (int i = 1; i <= n; i++)
		{
			scanf("%d", &arr[i]);
			ans[i] = -1;
			v[arr[i]].push_back(i);
		}

		for (int i = 1; i <= n; i++)
			v[i].push_back(n + 1);

		int filled = n + 1;
		for (int num = 1; num <= n; num++)
		{
			if (v[num].size() <= 2)
				continue;

			int maxd = 0;
			int siz = v[num].size();
			for (int i = 0; i < siz - 1; i++)
				maxd = max(maxd, v[num][i + 1] - v[num][i]);

			if (maxd < filled)
			{
				for (int i = maxd; i < filled; i++)
					ans[i] = num;

				filled = maxd;
			}
		}

		for (int i = 1; i <= n; i++)
			printf("%d ", ans[i]);
		printf("\n");
	}
}


#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <algorithm>
#include <set>
#include <vector>
#include <cmath>
#include <map>
#include <queue>
#include <climits>
#include <memory.h>
#include <bitset>
#include <time.h>
#include <functional>
#include <numeric>
#pragma comment(linker, "/STACK:360777216")

using LL = long long;
#define vi vector<int>
#define vs vector<string>
#define vvi vector<vector<int>>
#define vvll vector<vector<LL>>
#define vpii vector<pair<int, int>>
#define forn(i, start, end) for(int (i) = (start); (i) < (end); ++(i))
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define pii pair<int, int>
#define mp make_pair
#define vll vector<LL>
int M = 1000000007;
int INF = INT_MAX - 1000;
LL LLINF = 1e17;
int P = 31;
using namespace std;

LL t, tt, n, m, x, k, d, y, r, c, q;

int main() {
#ifdef _DEBUG
	freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
#else
	//freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
#endif
	ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	cin >> t;

	forn(ii, 0, t)
	{
		cin >> n;
		vi a(n);
		set<int> nums;
		int mini = 1e9;
		vll ans(n + 1, -1);
		map<int, set<int>> pos;
		forn(i, 0, n)
		{
			cin >> a[i];
			pos[a[i]].insert(i);
		}
		for (auto &cur_m : pos)
		{
			int max_diff = 0, last = -1;
			for (auto &cur_pos : cur_m.second)
			{
				max_diff = max(max_diff, cur_pos - last);
				last = cur_pos;
			}
			max_diff = max(max_diff, int(n) - last);
			forn(i, max_diff, n + 1)
			{
				if (ans[i] == -1) ans[i] = cur_m.first;
				else break;
			}
		}

		forn(i, 1, n + 1) cout << ans[i] << " ";
		cout << endl;

	}

	return 0;
}


#include<cstdio>
#include<iostream>
#include<vector>
#include<map>
#include<algorithm>

using namespace std;

int max(int a,int b)
{
	if(a>b)
	{
		return a;
	}
	else
	{
		return b;
	}
}

bool cmp(int a,int b)
{
	return a<b;
}

int main()
{
	int t;

	scanf("%d",&t);

	while(t--)
	{
		int n;

		scanf("%d",&n);

		vector<int> v;

		map<int,int> dis, bef, aft;

		for(int i=1;i<=n;++i)
		{
			int num;

			scanf("%d",&num);

			if(bef[num]==0)
			{
				bef[num] = 0;
			}

			if(aft[num]==0)
			{
				aft[num] = n + 1;
			}

			if(dis[num]==0)
			{
				dis[num] = i-bef[num];

				bef[num] = i;

				v.push_back(num);
			}
			else
			{
				dis[num] = max(dis[num],i-bef[num]);

				bef[num] = i;
			}

			//cout << dis[num] << endl;
		}

		for(int i=0;i<v.size();++i)
		{
			dis[v[i]] = max(dis[v[i]],aft[v[i]]-bef[v[i]]);

			//cout << v[i] << " " << dis[v[i]]<<endl;
		}

		sort(v.begin(),v.end(),cmp);

		for(int i=1;i<=n;++i)
		{
			int flag = 0;

			for(int j=0;j<v.size();++j)
			{
				if(dis[v[j]]<=i)
				{
					printf("%d ",v[j]);

					flag = 1;

					break;
				}
			}

			if(flag==0)
			{
				printf("-1 ");
			}
		}

		printf("\n");
	}

	return 0;
}


#include<cstdio>
#include<iostream>
#include<vector>
#include<map>
#include<algorithm>

using namespace std;

int max(int a,int b)
{
	if(a>b)
	{
		return a;
	}
	else
	{
		return b;
	}
}

bool cmp(int a,int b)
{
	return a<b;
}

int main()
{
	int t;

	scanf("%d",&t);

	while(t--)
	{
		int n;

		scanf("%d",&n);

		vector<int> v;

		map<int,int> dis, bef, aft;

		for(int i=1;i<=n;++i)
		{
			int num;

			scanf("%d",&num);

			if(bef[num]==0)
			{
				bef[num] = 0;
			}

			if(aft[num]==0)
			{
				aft[num] = n + 1;
			}

			if(dis[num]==0)
			{
				dis[num] = i-bef[num];

				bef[num] = i;

				v.push_back(num);
			}
			else
			{
				dis[num] = max(dis[num],i-bef[num]);

				bef[num] = i;
			}

			//cout << dis[num] << endl;
		}

		map<int,int> sum;

		for(int i=0;i<v.size();++i)
		{
			dis[v[i]] = max(dis[v[i]],aft[v[i]]-bef[v[i]]);

			if(sum[dis[v[i]]]==0)
			{
				sum[dis[v[i]]] = v[i];
			}
			else
			{
				if(v[i]<sum[dis[v[i]]])
				{
					sum[dis[v[i]]] = v[i];
				}
			}

			//cout << v[i] << " " << dis[v[i]]<<endl;
		}

		sort(v.begin(),v.end(),cmp);

		int ans = -1;

		for(int i=1;i<=n;++i)
		{
			if(sum[i]==0&&ans==-1)
			{
				printf("%d ",ans);
			}
			else
			if(ans==-1)
			{
				ans = sum[i];

				printf("%d ",ans);
			}
			else
			if(sum[i]==0)
			{
				printf("%d ",ans);
			}
			else
			{
				if(ans<sum[i])
				{
					printf("%d ",ans);
				}
				else
				{
					ans = sum[i];

					printf("%d ",ans);
				}
			}
		}

		printf("\n");
	}

	return 0;
}


#include "iostream"
#include "cstring"
#define ll long long
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
const ll mx=3e5+10;
using namespace std;
ll a[mx],loc[mx],dis[mx],ans[mx], n;
int main()
{
    IOS;
    ll T;
    cin>>T;
    for(ll lp=1;lp<=T;lp++){
        cin>>n;
        memset(loc,0,sizeof loc);
        memset(dis,0,sizeof dis);
        memset(ans,0,sizeof ans);
        for(ll i=1;i<=n;i++){
            cin>>a[i];
            dis[a[i]]=max(dis[a[i]],i-loc[a[i]]);//滚动记录两个数据大小为a[i]的数据之间的最大距离
            loc[a[i]]=i;
        }
        for(ll i=1;i<=n;i++){
            dis[a[i]]=max(n-loc[a[i]]+1,dis[a[i]]);//记录最后一个a[i]到末尾的距离
        }
        //dis[i]=对于v为i的值实现共有的最小距离size
        //ans[i]记录对于size为i的最小答案
        for(ll i=1;i<=n;i++)//对于v：1~n
        {
            if(ans[dis[i]]==0){
                //如果v=i存在， 那么对于该v需要size=dis[i]
                //ans[size]=i;对于该size有一个满足共有的数据i 并且是最小的数据
                //但是size+1可能就没有记录到该i 所以后续输出的时候需要res辅助记录最小amazingk
                ans[dis[i]]=i;
            }
        }
        ll res=-1;
        for(ll i=1;i<=n;i++){
            if(i!=1) cout<<" ";
            if(ans[i]==0){//取res
                cout<<res;
            }
            else{
                res=(res==-1)?ans[i]:min(res, ans[i]);//如果是-1就赋值，如果不是-1取最小值
                cout<<res;
            }
        }
        cout<<endl;
    }
    return 0;
}


#include<cstdio>
#include<cstring>
#include<math.h>
#include<stdlib.h>
#include<vector>
#include<algorithm>
using namespace std;
const int N=3*1e5+10;
const int inf=0x3f3f3f3f;
int a[N],n;
vector<int>v[N];
int pos[N];///pos[i]:�����Ϊiʱ�����������ж����ֵ���С����Ϊpos[i]
void init()
{
    for(int i=0; i<=n; i++)
    {
        v[i].clear();
        pos[i]=inf;
    }
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        init();
        for(int i=1; i<=n; i++)
        {
            scanf("%d",&a[i]);
            v[a[i]].push_back(i);
        }
        for(int i=1; i<=n; i++)///ö��ÿһ��i���ҵ�һ����С������k��i������������k�ж����ֹ�
        {
            int mx=0;
            if(!v[i].empty())
            {
                for(int j=1; j<v[i].size(); j++)
                    mx=max(mx,v[i][j]-v[i][j-1]);
                mx=max(mx,v[i].front());
                mx=max(mx,n-v[i].back()+1);///�ҵ�i��i֮����������࣬����඼�����㣬С����������
                pos[mx]=min(pos[mx],i);
            }
        }
        for(int i=2; i<=n; i++)///���䳤��Ϊi���������⣬���ȴ���i�ĸ�����
            pos[i]=min(pos[i],pos[i-1]);
        for(int i=1; i<n; i++)
        {
            if(pos[i]!=inf)
                printf("%d ",pos[i]);
            else
                printf("-1 ");
        }
        if(pos[n]!=inf)
            printf("%d\n",pos[n]);
        else
            printf("-1\n");
    }
    return 0;
}


#include<cstdio>
#include<cmath>
#include<vector>
#include<string>
#include<algorithm>
#include<queue>
#include<stack>
#include<set>
#include<map>
#include<functional>
#include<cstring>

using namespace std;

int main()
{
	//freopen("input.txt", "r", stdin);

	int cases;

	scanf("%d", &cases);

	for (int tc = 0; tc < cases; tc++)
	{
		int n;

		scanf("%d", &n);

		int last[300001];
		int lmax[300001] = { 0, };

		for (int i = 1; i <= n; i++)
		{
			last[i] = -1;
		}

		for (int i = 0; i < n; i++)
		{
			int input;

			scanf("%d", &input);

			if (i - last[input] > lmax[input])
			{
				lmax[input] = i - last[input];
			}

			last[input] = i;
		}

		for (int i = 1; i <= n; i++)
		{
			if (last[i] != -1 && n - last[i] > lmax[i])
			{
				lmax[i] = n - last[i];
			}
		}

		int val[300001];
		val[0] = 0;

		for (int i = 1; i <= n; i++)
		{
			val[i] = val[i - 1];

			if (lmax[i] != 0 && (val[i] == 0 || lmax[i] < val[i]))
			{
				val[i] = lmax[i];
			}
		}

		int ptr = n;

		int sol[300001];

		for (int i = 1; i <= n; i++)
		{
			while (ptr&&val[ptr] <= i && val[ptr])
			{
				ptr--;
			}

			if (ptr == n)
			{
				printf("-1 ");

				continue;
			}

			printf("%d ", ptr + 1);
		}

		printf("\n");
	}

	return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <math.h>
#include <string>
#include <set>
#include <map>
#include <stdio.h>
using namespace std;

#define ll long long
#define modu 1000000007

ll n, T, p, ans, t, curr, mini = modu, maxi;
vector <ll> v;
vector <vector <ll> > pos(300010);
ll k[300010];

int main()
{
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);

    cin >> T;
    while(T--) {
        v.clear();
        mini = modu;
        cin >> n;
        for(int i = 0; i < n; ++i) {
            cin >> p;
            p--;
            v.push_back(p);
            if(pos[p].size() == 0) {
                pos[p].push_back(-1);
            }
            pos[p].push_back(i);
            k[i] = -1;
            mini = min(mini, p);
        }
        k[n] = -1;
        for(int i = 0; i < n; ++i) {
            if(pos[i].size() == 0) continue;
            else pos[i].push_back(n);
            maxi = -modu;
            for(int j = 1; j < pos[i].size(); ++j) {
                maxi = max(maxi, pos[i][j] - pos[i][j - 1]);
            }
            if(maxi != -modu && k[maxi] == -1) {
                k[maxi] = i + 1;
            }
        }
        k[n] = mini + 1;

        for(int i = 1; i <= n; ++i) {
            if(k[i] == -1) {
                k[i] = k[i - 1];
            }
            else {
                if(k[i - 1] != -1) {
                    k[i] = min(k[i], k[i - 1]);
                }
            }
            cout << k[i] << ' ';
        }
        cout << endl;

        for(int i = 0; i < n; ++i) {
            pos[i].clear();
        }
    }

    return 0;
}


#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=3e5+100;
typedef long long LL;
const LL inf=1e18;
LL ans[maxn];
vector<LL>v[maxn];
int main(void)
{
  cin.tie(0);std::ios::sync_with_stdio(false);
  LL t;cin>>t;
  while(t--)
  {
  	LL n;cin>>n;
  	for(LL i=0;i<=n+10;i++) ans[i]=inf,v[i].clear();
  	for(LL i=1;i<=n;i++){
  		LL x;cin>>x;v[x].push_back(i);
	}
	for(LL i=1;i<=n;i++)
	{
		if(!v[i].empty())
		{
			LL mx=0;
			for(LL j=1;j<v[i].size();j++)
			{
				mx=max(mx,v[i][j]-v[i][j-1]);
			}
			mx=max(mx,v[i].front());
			mx=max(mx,n-v[i].back()+1);
			ans[mx]=min(ans[mx],i);
		}
	}
	for(LL i=2;i<=n;i++) ans[i]=min(ans[i],ans[i-1]);
	for(LL i=1;i<=n;i++){
		if(ans[i]<inf) cout<<ans[i]<<" ";
		else cout<<"-1"<<" ";
	}
	cout<<endl;
  }
return 0;
}


#include<stdio.h>
const int N=3e5+5;
int t,n;
int a[N],d[N],last[N],ans[N];
int max(int x,int y)
{
	return x>y?x:y;
}
int main(){
	scanf("%d",&t);
	while(t--){
		scanf("%d",&n);
		for(int i=1;i<=n;i++){
			scanf("%d",&a[i]);
			last[i]=d[i]=0,ans[i]=-1;
		}
		for(int i=1;i<=n;i++){
			int x=a[i];
			d[x]=max(d[x],i-last[x]);
			last[x]=i;
		}
		for(int i=1;i<=n;i++){
			d[i]=max(d[i],n-last[i]+1);
			for(int j=d[i];j<=n&&ans[j]==-1;j++) ans[j]=i;
		}
		for(int i=1;i<=n;i++) printf("%d ",ans[i]);
		printf("\n");
	}
	return 0;
}


#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<iostream>
#include<queue>
#include<string>
#include<map>
#include<set>
#include<stack>
#include<vector>
#include <iomanip>
#include <ctime>
#include <fstream>
#include<stdlib.h>

#define ll long long
#define mt(a) memset(a,0,sizeof(a))
#define MAXI 2000000010
#define MAXLL 4e18+9
#define PAI pair<int,int>
#define eps 1e-6
#define ls (p << 1)
#define rs (p << 1 | 1)
#define PI acos(-1.0)
#define rei(a) scanf("%d",&a);
#define rell(a) scanf("%lld",&a);
#define DZ int T;scanf("%d",&T);while (T--)
//#define double long double
#define all(x) x.begin(), x.end()
#define unq(x) x.erase(unique(x.begin(), x.end()), x.end())
//#define inf 0x3f3f3f3f
const int maxn = 2e6 + 9;

using namespace std;

int a[maxn];
int b[maxn],c[maxn],d[maxn];
int main()
{
	DZ
	{
		int n;
		rei(n);
		for (int i = 1; i <= n; i++)
		{
			rei(a[i]);
			b[i] = 0;
			c[i] = -1;
			d[i] = -1;
		}

		for (int i = 1; i <= n; i++)
		{
			c[a[i]] = max(i - b[a[i]], c[a[i]]);
			b[a[i]] = i;
		}
		for (int i = 1; i <= n; i++)
		{
			if (b[i] != 0)
				c[a[i]] = max(n + 1 - b[a[i]], c[a[i]]);
		}

		int end = n;
		for (int i = 1; i <= n; i++)
		{
			if (c[i] != -1 && c[i]<=end)
			{
				for (int j = c[i]; j <= end; j++)
					d[j] = i;
				end = c[i] - 1;
			}
		}

		for (int i = 1; i <= n; i++)
			printf("%d ", d[i]);
		putchar(10);
	}

	return 0;
}


#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<iostream>
#include<queue>
#include<string>
#include<map>
#include<set>
#include<stack>
#include<vector>
#include <iomanip>
#include <ctime>
#include <fstream>
#include<stdlib.h>

#define ll long long
#define mt(a) memset(a,0,sizeof(a))
#define MAXI 2000000010
#define MAXLL 4e18+9
#define PAI pair<int,int>
#define eps 1e-6
#define ls (p << 1)
#define rs (p << 1 | 1)
#define PI acos(-1.0)
#define rei(a) scanf("%d",&a);
#define rell(a) scanf("%lld",&a);
#define DZ int T;scanf("%d",&T);while (T--)
//#define double long double
#define all(x) x.begin(), x.end()
#define unq(x) x.erase(unique(x.begin(), x.end()), x.end())
//#define inf 0x3f3f3f3f
const int maxn = 2e6 + 9;

using namespace std;

int a[maxn];
int b[maxn],c[maxn],d[maxn];
int main()
{
	DZ
	{
		int n;
		rei(n);
		for (int i = 1; i <= n; i++)
		{
			rei(a[i]);
			b[i] = 0;
			c[i] = -1;
			d[i] = -1;
		}

		for (int i = 1; i <= n; i++)
		{
			c[a[i]] = max(i - b[a[i]], c[a[i]]);
			b[a[i]] = i;
		}
		for (int i = 1; i <= n; i++)
		{
			if (b[a[i]] != 0)
				c[a[i]] = max(n + 1 - b[a[i]], c[a[i]]);
		}

		int end = n;
		for (int i = 1; i <= n; i++)
		{
			if (c[i] != -1 && c[i]<=end)
			{
				for (int j = c[i]; j <= end; j++)
					d[j] = i;
				end = c[i] - 1;
			}
		}

		for (int i = 1; i <= n; i++)
			printf("%d ", d[i]);
		putchar(10);
	}

	return 0;
}


import math
import sys

class Read:
    @staticmethod
    def string():
        return input()

    @staticmethod
    def int():
        return int(input())

    @staticmethod
    def list(sep=' '):
        return input().split(sep)

    @staticmethod
    def list_int(sep=' '):
        return list(map(int, input().split(sep)))

def solve():
    n = Read.int()
    a = Read.list_int()
    tmp = {}
    last = {}
    for i in range(n):
        v = i
        if a[i] in last:
            v = i - last[a[i]] - 1
        last[a[i]] = i
        if a[i] in tmp:
            if v > tmp[a[i]]:
                tmp[a[i]] = v
        else:
            tmp[a[i]]  = v
    for k, v in last.items():
        v = n - 1 - v
        if v > tmp[k]:
            tmp[k] = v

    tmp_s = sorted(list(tmp.keys()))

    res = []
    l = 0
    for i in tmp_s:
        r = n - tmp[i]
        for j in range(l, r):
            res.append(str(i))
        if(r > l):
            l = r
    for i in range(n - len(res)):
        res.append('-1')
    res.reverse()
    print(' '.join(res))

# query_count = 1
query_count = Read.int()
while query_count:
    query_count -= 1
    solve()


import math
import sys

class Read:
    @staticmethod
    def string():
        return input()

    @staticmethod
    def int():
        return int(input())

    @staticmethod
    def list(sep=' '):
        return input().split(sep)

    @staticmethod
    def list_int(sep=' '):
        return list(map(int, input().split(sep)))

def solve():
    n = Read.int()
    a = Read.list_int()
    tmp = {}
    for i in range(n):
        if a[i] in tmp:
            tmp[a[i]].append(i)
        else:
            tmp[a[i]] = [i]

    tmp_s = sorted(list(tmp.keys()), reverse=True)
    res = []
    for i in range(n):
        res.append('-1')
    for i in tmp_s:
        v = tmp[i]
        k = [v[0], n - v[-1] - 1]
        for j in range(len(v) - 1):
            k.append(v[j + 1] - v[j] - 1)
        m = max(k)
        for j in range(n - 1, m - 1, -1):
            res[j] = str(i)
    print(' '.join(res))

# query_count = 1
query_count = Read.int()
while query_count:
    query_count -= 1
    solve()


import math
import sys

class Read:
    @staticmethod
    def string():
        return input()

    @staticmethod
    def int():
        return int(input())

    @staticmethod
    def list(sep=' '):
        return input().split(sep)

    @staticmethod
    def list_int(sep=' '):
        return list(map(int, input().split(sep)))

def solve():
    n = Read.int()
    a = Read.list_int()
    tmp = {}
    last = {}
    for i in range(n):
        v = i
        if a[i] in last:
            v = i - last[a[i]] - 1
        last[a[i]] = i
        if a[i] in tmp:
            if v > tmp[a[i]]:
                tmp[a[i]] = v
        else:
            tmp[a[i]]  = v
    for k, v in last.items():
        v = n - 1 - v
        if v > tmp[k]:
            tmp[k] = v

    tmp_s = sorted(list(tmp.keys()), reverse=True)

    res = []
    for i in range(n):
        res.append('-1')

    for i in tmp_s:
        for j in range(n - 1, tmp[i] - 1, -1):
            res[j] = str(i)

    print(' '.join(res))

# query_count = 1
query_count = Read.int()
while query_count:
    query_count -= 1
    solve()


import math
import sys

class Read:
    @staticmethod
    def string():
        return input()

    @staticmethod
    def int():
        return int(input())

    @staticmethod
    def list(sep=' '):
        return input().split(sep)

    @staticmethod
    def list_int(sep=' '):
        return list(map(int, input().split(sep)))

def solve():
    n = Read.int()
    a = Read.list_int()
    a_s = sorted(a)
    tmp = {}
    for i in range(n):
        if a[i] in tmp:
            tmp[a[i]].append(i)
        else:
            tmp[a[i]] = [i]

    tmp_s = sorted(list(tmp.keys()), reverse=True)
    res = []
    for i in range(n):
        res.append('-1')
    for i in tmp_s:
        v = tmp[i]
        k = [v[0], n - v[-1] - 1]
        for j in range(len(v) - 1):
            k.append(v[j + 1] - v[j] - 1)
        m = max(k)
        for j in range(n - 1, m - 1, -1):
            res[j] = str(i)
    print(' '.join(res))

# query_count = 1
query_count = Read.int()
while query_count:
    query_count -= 1
    solve()


import collections

############ ---- Input Functions ---- ############
def inp():
    return(int(input()))
def inlt():
    return(list(map(int,input().split())))
def insr():
    s = input()
    return(list(s[:len(s) - 1]))
def invr():
    return(map(int,input().split()))

t = inp()
for _ in range(t):
    _, a = inp(), inlt()
    res = [-1] * len(a)
    idxs = collections.defaultdict(list)
    max_int = {}
    last_i = {}
    for i, num in enumerate(a):
        if num not in max_int:
            max_int[num] = i+1
            last_i[num] = i
        else:
            max_int[num] = max(i-last_i[num], max_int[num])
            last_i[num] = i

    for num in max_int:
        mx = max(max_int[num], len(a)-last_i[num])
        for i in range(mx-1, len(res)):
            if res[i] == -1 or res[i] > num:
                res[i] = num

    print(" ".join([str(x) for x in res]))


import collections

############ ---- Input Functions ---- ############
def inp():
    return(int(input()))
def inlt():
    return(list(map(int,input().split())))
def insr():
    s = input()
    return(list(s[:len(s) - 1]))
def invr():
    return(map(int,input().split()))

t = inp()
for _ in range(t):
    _, a = inp(), inlt()
    res = [-1] * len(a)
    idxs = collections.defaultdict(list)
    max_int = {}
    last_i = {}
    for i, num in enumerate(a):
        if num not in max_int:
            max_int[num] = i+1
            last_i[num] = i
        else:
            max_int[num] = max(i-last_i[num], max_int[num])
            last_i[num] = i
    for num in max_int:
        max_int[num] = max(max_int[num], len(a)-last_i[num])

    ints = sorted(max_int.keys(), key=lambda a : (max_int[a], a))
    best = ints[0]
    inti = 0
    for i in range(max_int[ints[0]], len(res)+1):
        while inti < len(ints) and i == max_int[ints[inti]]:
            best = min(ints[inti], best)
            inti += 1
        res[i-1] = best

    print(" ".join([str(x) for x in res]))


import collections

############ ---- Input Functions ---- ############
def inp():
    return(int(input()))
def inlt():
    return(list(map(int,input().split())))
def insr():
    s = input()
    return(list(s[:len(s) - 1]))
def invr():
    return(map(int,input().split()))

t = inp()
for _ in range(t):
    _, a = inp(), inlt()
    res = [-1] * len(a)
    idxs = collections.defaultdict(list)
    for i, num in enumerate(a):
        idxs[num].append(i)

    for num, lst in idxs.items():
        lst.append(len(a))
        mx = lst[0]+1
        for i in range(len(lst) - 1):
            mx = max(mx, lst[i+1]-lst[i])
        for i in range(mx-1, len(res)):
            if res[i] == -1 or res[i] > num:
                res[i] = num

    print(" ".join([str(x) for x in res]))


import sys
input = sys.stdin.readline

############ ---- Input Functions ---- ############
def inp():
    return(int(input()))
def inlt():
    return(list(map(int,input().split())))

test_cases = inp()
max_poss = 3123456

def solve():
    n = inp()
    arr = inlt()

    max_dist = {}
    last_ind = {}

    for ind, num in enumerate(arr):
        dist = ind - last_ind.get(num, -1)
        if num not in max_dist:
            max_dist[num] = dist
        else:
            max_dist[num] = max(max_dist[num], dist)
        last_ind[num] = ind

    for num, last_index in last_ind.items():
        dist = n - last_index
        max_dist[num] = max(max_dist[num], dist)

    answers_rev = {}

    for num, dist in max_dist.items():
        if dist not in answers_rev:
            answers_rev[dist] = num
        else:
            answers_rev[dist] = min(answers_rev[dist], num)

    ans = ""
    min_number_found = None

    for i in range(1, n+1):
        answer = answers_rev.get(i, max_poss)

        if answer != max_poss:
            if min_number_found is None:
                min_number_found = answer

            if answer < min_number_found:
                min_number_found = answer

        if min_number_found is not None:
            ans += "{}".format(min_number_found)
        else:
            ans += "-1".format(min_number_found)

        if i < n:
            ans += " "
        else:
            ans += "\n"

    print(ans)

for test in range(test_cases):
    solve()


import sys

# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')

input = sys.stdin.readline

t = int(input())
for x in range(t):
	n = int(input())
	A = list(map(int, input().split(' ')))
	ans = [-1 for _ in range(n)]
	for k in range(n):
		common = set(A[:k+1])
		for i in range(n - k):
			common &= set(A[i: i+k+1])
		if common:
			ans[k] = min(common)
	print(' '.join(map(str, ans)))


import sys

# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')

input = sys.stdin.readline

def solve_slow(A, n):
	ans = [-1 for _ in range(n)]
	for k in range(n):
		common = set(A[:k+1])
		for i in range(n - k):
			common &= set(A[i: i+k+1])
		if common:ans = [-1 for _ in range(n)]
	for k in range(n):
		common = set(A[:k+1])
		for i in range(n - k):
			common &= set(A[i: i+k+1])
		if common:
			ans[k] = min(common)
	return ans

def solve_fast(A, n):
	ans = [-1 for _ in range(n)]
	counter = {}
	for index, a in enumerate(A):
		if a not in counter:
			counter[a] = [index]
		else:
			counter[a].append(index)
	for i in range(1, n+1):
		if i not in counter:
			continue
		indices = counter[i]
		indices.sort()
		segment_size = max(
			indices[0] + 1,
			n - indices[-1]
		)
		for j in range(len(indices)-1):
			diff = indices[j+1] - indices[j]
			segment_size = max(segment_size, diff)

		if ans[segment_size - 1] == -1:
			ans[segment_size - 1] = i
		# print(i, ' ', indices, ' segment = ', segment_size)
	# buble best answer up
	for i in range(1, n):
		if ans[i-1] == -1:
			continue
		if ans[i] == -1 or ans[i-1] < ans[i]:
			ans[i] = ans[i-1]
	return ans

t = int(input())
for x in range(t):
	n = int(input())
	A = list(map(int, input().split(' ')))
	# ans = solve_slow(A, n)
	# print(' '.join(map(str, ans)))

	ans = solve_fast(A, n)
	print(' '.join(map(str, ans)))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int,input().split()))
	b = [[0] for i in range(n)]
	for i in range(n):
		f = a[i]-1
		b[f].append(i+1)
	#print(b)
	for i in range(n):
		b[i].append(n+1)
	#print(b)
	d = [[] for i in range(n)]
	ch = [-10]*n
	for i in range(n):
		s = b[i]
		for j in range(len(s)-1):
			v = s[j+1]-s[j]
			d[i].append(v)
		ch[i] = max(d[i])-1
	#print(ch)
	g = [-1]*n
	marked = [False]*n
	for j in range(n):
		for i in range(n-1,-1,-1):
			if i >= ch[j] and marked[i] == False:
				g[i] = j + 1
				marked[i] = True
				continue

	print(*g)


#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int a[N];
int main()
{
	ios::sync_with_stdio(false);
	int T;
	scanf("%d", &T);
	while (T--)
	{
		int n;
		cin >> n;
		for (int i = 1; i <= n; i++)
			cin >> a[i];
		sort(a + 1, a + n + 1);
		if (n <= 2)
		{
			cout << 0 << endl;
		}
		else
		{
			int ans = min(n - 2, a[n - 1] - 1);
			cout << ans << endl;
		}
	}
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int a[N];
int main()
{
	int T;
	scanf("%d", &T);
	while (T--)
	{
		int n;
		cin >> n;
		for (int i = 1; i <= n; i++)
			cin >> a[i];
		sort(a + 1, a + n + 1);
		if (n <=2)
		{
			cout << 0 <<endl;
		}
		int t1 = a[n];
		int t2 = a[n - 1];
		int test =a[n-1]-1;
		int ans = min(n-2, a[n - 1]-1);
		cout << ans << endl;
	}

}


#include <vector>
#include <iostream>
#include <queue>
#include <cmath>
#include <algorithm>
#include <string>

#define int long long

using namespace std;

struct g {
	int a;
	int b;
};

bool comp(g a, g b) {
	return a.a > b.a;
}

bool compa(int a, int b) {
	return a > b;
}

signed main() {
	int t = 0;
	cin >> t;
	vector<int> reta(t);
	for (int j = 0; j < t; j++) {
		int n;
		cin >> n;
		int max1 = -1, max2 = -1;
		for (int i = 0; i < n; i++) {
			int buff;
			cin >> buff;
			if (buff >= max1) {
				max2 = max1;
				max1 = buff;
			}
		}
		int ret = min(min(max1, max2) - 1, n - 2);
		if (ret < 1)
			reta[j] = 0;
		else
			reta[j] = ret;
	}
	for(int i = 0; i < t; i++)
	cout<<reta[j]<<'\n';
	return 0;
}


#include <vector>
#include <iostream>
#include <queue>
#include <cmath>
#include <algorithm>
#include <string>

#define int long long

using namespace std;

struct g {
	int a;
	int b;
};

bool comp(g a, g b) {
	return a.a > b.a;
}

bool compa(int a, int b) {
	return a > b;
}

signed main() {
	int t = 0;
	cin >> t;
	for (int j = 0; j < t; j++) {
		int n;
		cin >> n;
		int max1 = -1, max2 = -1;
		for (int i = 0; i < n; i++) {
			int buff;
			cin >> buff;
			if (buff >= max1) {
				max2 = max1;
				max1 = buff;
			}
		}
		cout << min(min(max1, max2) - 1, n - 2);
	}
	return 0;
}


#include <vector>
#include <iostream>
#include <queue>
#include <cmath>
#include <algorithm>
#include <string>

#define int long long

using namespace std;

struct g {
	int a;
	int b;
};

bool comp(g a, g b) {
	return a.a > b.a;
}

bool compa(int a, int b) {
	return a > b;
}

signed main() {
	int t = 0;
	cin >> t;
	for (int j = 0; j < t; j++) {
		int n;
		cin >> n;
		int max1 = -1, max2 = -1;
		for (int i = 0; i < n; i++) {
			int buff;
			cin >> buff;
			if (buff >= max1) {
				max2 = max1;
				max1 = buff;
			}
		}
		cout << min(min(max1, max2) - 1, n - 2)<<"\n";
	}
	return 0;
}


#include <vector>
#include <iostream>
#include <queue>
#include <cmath>
#include <algorithm>
#include <string>

#define int long long

using namespace std;

struct g {
	int a;
	int b;
};

bool comp(g a, g b) {
	return a.a > b.a;
}

bool compa(int a, int b) {
	return a > b;
}

signed main() {
	int t = 0;
	cin >> t;
	vector<int> reta(t);
	for (int j = 0; j < t; j++) {
		int n;
		cin >> n;
		int max1 = -1, max2 = -1;
		for (int i = 0; i < n; i++) {
			int buff;
			cin >> buff;
			if (buff >= max1) {
				max2 = max1;
				max1 = buff;
			}
		}
		int ret = min(min(max1, max2) - 1, n - 2);
		if (ret < 1)
			reta[j] = 0;
		else
			reta[j] = ret;
	}
	for(int i = 0; i < t; i++;)
	cout<<reta[j]<<'\n';
	return 0;
}


#include <vector>
#include <iostream>
#include <queue>
#include <cmath>
#include <algorithm>
#include <string>

#define int long long

using namespace std;

struct g {
	int a;
	int b;
};

bool comp(g a, g b) {
	return a.a > b.a;
}

bool compa(int a, int b) {
	return a > b;
}

signed main() {
	int t = 0;
	cin >> t;
	for (int j = 0; j < t; j++) {
		int n;
		cin >> n;
		int max1 = -1, max2 = -1;
		for (int i = 0; i < n; i++) {
			int buff;
			cin >> buff;
			if (buff >= max1) {
				max2 = max1;
				max1 = buff;
			}
		}
		int ret = min(min(max1, max2) - 1, n - 2);
		if (ret < 1)
			cout << 0 << "\n";
		else
			cout << ret << "\n";
	}
	return 0;
}


#include <vector>
#include <iostream>
#include <queue>
#include <cmath>
#include <algorithm>
#include <string>

#define int long long

using namespace std;

struct g {
	int a;
	int b;
};

bool comp(g a, g b) {
	return a.a > b.a;
}

bool compa(int a, int b) {
	return a > b;
}

signed main() {
	int t = 0;
	cin >> t;
	vector<int> reta(t);
	for (int j = 0; j < t; j++) {
		int n;
		cin >> n;
		int max1 = -1, max2 = -1;
		for (int i = 0; i < n; i++) {
			int buff;
			cin >> buff;
			if (buff >= max1) {
				max2 = max1;
				max1 = buff;
			}
		}
		int ret = min(min(max1, max2) - 1, n - 2);
		if (ret < 1)
			reta[j] = 0;
		else
			reta[j] = ret;
	}
	for(int i = 0; i < t; i++)
	cout<<reta[i]<<'\n';
	return 0;
}


#include <vector>
#include <iostream>
#include <queue>
#include <cmath>
#include <algorithm>
#include <string>

#define int long long

using namespace std;

struct g {
	int a;
	int b;
};

bool comp(g a, g b) {
	return a.a > b.a;
}

bool compa(int a, int b) {
	return a > b;
}

signed main() {
	int t = 0;
	cin >> t;
	for (int j = 0; j < t; j++) {
		int n;
		cin >> n;
		int max1 = -1, max2 = -1;
		for (int i = 0; i < n; i++) {
			int buff;
			cin >> buff;
			if (buff >= max1) {
				max2 = max1;
				max1 = buff;
			}
		}
		int ret = min(min(max1, max2) - 1, n - 2);
		if (ret >= 1)
			cout << 0 << "\n";
		else
			cout << ret << "\n";
	}
	return 0;
}


#include <vector>
#include <iostream>
#include <queue>
#include <cmath>
#include <algorithm>
#include <string>

#define int long long

using namespace std;

struct g {
	int a;
	int b;
};

bool comp(g a, g b) {
	return a.a > b.a;
}

bool compa(int a, int b) {
	return a > b;
}

signed main() {
	int t = 0;
	cin >> t;
	vector<int> reta(t);
	for (int j = 0; j < t; j++) {
		int n;
		cin >> n;
		vector<int> vec(n);
		for(int i = 0; i < n; i++)
		cin>>vec[i];
		sort(vec.begin(), vec.end());
		cout<<min(vec[n-2] - 1, n-2)<<"\n";
	}
	return 0;
}


/////////////////////////////////////////////////////////////////////////////
//                                                                         //
//        * *       * * *     *   *       *     * * *     *         *      //
//      *     *   *       *   *   *       *   *       *   * *       *      //
//      *     *   *       *   *     *   *     *       *   *   *     *      //
//      * * *     * * * * *   *       *       * * * * *   *     *   *      //
//      * *       *       *   *       *       *       *   *       * *      //
//      *   *     *       *   *       *       *       *   *         *      //
//      *     *   *       *   *       *       *       *   *         *      //
//                                                                         //
/////////////////////////////////////////////////////////////////////////////

#include <bits/stdc++.h>
#include <cstdlib>
#include <cmath>
#include <stdio.h>
#include <math.h>

#define     fRead           freopen("input.txt","r",stdin)
#define     fWrite          freopen("output.txt","w",stdout)
#define     fast            ios_base::sync_with_stdio(false);cin.tie(NULL)

#define     ll              long long int
#define     ul              unsigned long long int
#define     dl              double
#define     st              string

#define     pb              push_back
#define     po              pop_back

#define     nl              endl
#define     rt              return 0

#define     N               cout << "No" << endl
#define     Y               cout << "Yes" << endl

#define     gcd(a, b)       __gcd(a, b)
#define     lcm(a, b)       (a * b) / gcd(a, b)

#define     all(v)          v.begin(),v.end()
#define     mem(a,v)        memset(a,v,sizeof(a))
#define     mod             1000000007
#define     mp              make_pair
#define     ins             insert
#define     rev             reverse
#define     _max            *max_element
#define     _min            *min_element
#define     SUM             accumulate
#define     BS              binary_search

#define     vec             vector <ll>
#define     PL              pair <ll,ll>
#define     vecp            vector < pair <ll, ll> >
#define     vecpp           vector < pair <ll, pair <ll, ll> > >
#define     se              set <ll>
#define     mapi            map<ll,ll>

#define     rep(i, l, r)        for(long long i = l; i<r; i++)
#define     repi(p, l, r, i)    for(long long p = l; p<r; p+=i)
#define     repb(i, r, l)       for(long long i = r; i>l; i--)
#define     repbd(p, r, l, d)   for(long long p = r; i>l; i-=d)

#define     max3(a, b, c)       max(a, max(b, c))
#define     max4(a, b, c, d)    max(max(a, b), max(c, d))
#define     min3(a, b, c)       min(a, min(b, c))
#define     min4(a, b, c, d)    min(min(a, b), min(c, d))

#define     vsort(v)            sort(v.begin(),v.end())
#define     all(container)      container.begin(), container.end()
#define     iterate(v, it)      for(vector< long long >::const_iterator it = v.begin(); it != v.end(); it++)

#define     BIG                 300000

using namespace std;

bool sortinrev(const pair<int,int> &a,
               const pair<int,int> &b)
{
       return (a.first > b.first);
}

int sumofdigits(string numinstring){
    int sum = 0;
    rep(i, 0, numinstring.size()){
        sum += numinstring[i] - '0' ;
    }
    return sum;
}

int checkDiffDigits(string str){
    for(int i = 0; i<str.size(); i++){
        for(int j = i+1; j<str.size();j++){
            if(str[i] == str[j]){
                return false;
                break;
            }
        }
    }
    return true;
}

/* Function to check if x is power of 2*/
bool isPowerOfTwo (long long x)
{
  /* First x in the below expression is
    for the case when x is 0 */
  return x && (!(x&(x-1)));
}

long long digitNO(long long num){
    return floor(log10(num)) + 1;
}

string converttostring(long long n){
    string s;
    stringstream ss;
    ss << n;
    s = ss.str();

    return s;
}

long long reversedigits(long long number){
    long long reverse = 0;
    long long rem;
    while(number!=0)
  {
     rem=number%10;
     reverse=reverse*10+rem;
     number/=10;
  }

  return reverse;
}

main(){
    int t; cin >> t;
    long long n;

    while (t--)
    {
        /* code */
        cin >> n;
        long long k = n-2;
        long long c = 0, one = 1;
        long long a[n];
        rep(i, 0, n){
            cin >> a[i];
        }
        sort(a, a+n);
        cout << min(a[n-2], k);
    }

}


/////////////////////////////////////////////////////////////////////////////
//                                                                         //
//        * *       * * *     *   *       *     * * *     *         *      //
//      *     *   *       *   *   *       *   *       *   * *       *      //
//      *     *   *       *   *     *   *     *       *   *   *     *      //
//      * * *     * * * * *   *       *       * * * * *   *     *   *      //
//      * *       *       *   *       *       *       *   *       * *      //
//      *   *     *       *   *       *       *       *   *         *      //
//      *     *   *       *   *       *       *       *   *         *      //
//                                                                         //
/////////////////////////////////////////////////////////////////////////////

#include <bits/stdc++.h>
#include <cstdlib>
#include <cmath>
#include <stdio.h>
#include <math.h>

#define     fRead           freopen("input.txt","r",stdin)
#define     fWrite          freopen("output.txt","w",stdout)
#define     fast            ios_base::sync_with_stdio(false);cin.tie(NULL)

#define     ll              long long int
#define     ul              unsigned long long int
#define     dl              double
#define     st              string

#define     pb              push_back
#define     po              pop_back

#define     nl              endl
#define     rt              return 0

#define     N               cout << "No" << endl
#define     Y               cout << "Yes" << endl

#define     gcd(a, b)       __gcd(a, b)
#define     lcm(a, b)       (a * b) / gcd(a, b)

#define     all(v)          v.begin(),v.end()
#define     mem(a,v)        memset(a,v,sizeof(a))
#define     mod             1000000007
#define     mp              make_pair
#define     ins             insert
#define     rev             reverse
#define     _max            *max_element
#define     _min            *min_element
#define     SUM             accumulate
#define     BS              binary_search

#define     vec             vector <ll>
#define     PL              pair <ll,ll>
#define     vecp            vector < pair <ll, ll> >
#define     vecpp           vector < pair <ll, pair <ll, ll> > >
#define     se              set <ll>
#define     mapi            map<ll,ll>

#define     rep(i, l, r)        for(long long i = l; i<r; i++)
#define     repi(p, l, r, i)    for(long long p = l; p<r; p+=i)
#define     repb(i, r, l)       for(long long i = r; i>l; i--)
#define     repbd(p, r, l, d)   for(long long p = r; i>l; i-=d)

#define     max3(a, b, c)       max(a, max(b, c))
#define     max4(a, b, c, d)    max(max(a, b), max(c, d))
#define     min3(a, b, c)       min(a, min(b, c))
#define     min4(a, b, c, d)    min(min(a, b), min(c, d))

#define     vsort(v)            sort(v.begin(),v.end())
#define     all(container)      container.begin(), container.end()
#define     iterate(v, it)      for(vector< long long >::const_iterator it = v.begin(); it != v.end(); it++)

#define     BIG                 300000

using namespace std;

bool sortinrev(const pair<int,int> &a,
               const pair<int,int> &b)
{
       return (a.first > b.first);
}

int sumofdigits(string numinstring){
    int sum = 0;
    rep(i, 0, numinstring.size()){
        sum += numinstring[i] - '0' ;
    }
    return sum;
}

int checkDiffDigits(string str){
    for(int i = 0; i<str.size(); i++){
        for(int j = i+1; j<str.size();j++){
            if(str[i] == str[j]){
                return false;
                break;
            }
        }
    }
    return true;
}

/* Function to check if x is power of 2*/
bool isPowerOfTwo (long long x)
{
  /* First x in the below expression is
    for the case when x is 0 */
  return x && (!(x&(x-1)));
}

long long digitNO(long long num){
    return floor(log10(num)) + 1;
}

string converttostring(long long n){
    string s;
    stringstream ss;
    ss << n;
    s = ss.str();

    return s;
}

long long reversedigits(long long number){
    long long reverse = 0;
    long long rem;
    while(number!=0)
  {
     rem=number%10;
     reverse=reverse*10+rem;
     number/=10;
  }

  return reverse;
}

main(){
    int t; cin >> t;
    long long n;

    while (t--)
    {
        /* code */
        cin >> n;
        long long k = n-2;
        long long c = 0, one = 1;
        long long a[n];
        rep(i, 0, n){
            cin >> a[i];
            if(a[i] >= k+1){
                c++;
            }
            if(a[i] < 1){
                one = 0;
            }
        }
        if(k<1) {
            cout << 0 << endl;
            continue;
        }
        if(c>=2) cout << k << endl;
        else cout << max(k-c, n-k-c) << endl;
    }

}


/////////////////////////////////////////////////////////////////////////////
//                                                                         //
//        * *       * * *     *   *       *     * * *     *         *      //
//      *     *   *       *   *   *       *   *       *   * *       *      //
//      *     *   *       *   *     *   *     *       *   *   *     *      //
//      * * *     * * * * *   *       *       * * * * *   *     *   *      //
//      * *       *       *   *       *       *       *   *       * *      //
//      *   *     *       *   *       *       *       *   *         *      //
//      *     *   *       *   *       *       *       *   *         *      //
//                                                                         //
/////////////////////////////////////////////////////////////////////////////

#include <bits/stdc++.h>
#include <cstdlib>
#include <cmath>
#include <stdio.h>
#include <math.h>

#define     fRead           freopen("input.txt","r",stdin)
#define     fWrite          freopen("output.txt","w",stdout)
#define     fast            ios_base::sync_with_stdio(false);cin.tie(NULL)

#define     ll              long long int
#define     ul              unsigned long long int
#define     dl              double
#define     st              string

#define     pb              push_back
#define     po              pop_back

#define     nl              endl
#define     rt              return 0

#define     N               cout << "No" << endl
#define     Y               cout << "Yes" << endl

#define     gcd(a, b)       __gcd(a, b)
#define     lcm(a, b)       (a * b) / gcd(a, b)

#define     all(v)          v.begin(),v.end()
#define     mem(a,v)        memset(a,v,sizeof(a))
#define     mod             1000000007
#define     mp              make_pair
#define     ins             insert
#define     rev             reverse
#define     _max            *max_element
#define     _min            *min_element
#define     SUM             accumulate
#define     BS              binary_search

#define     vec             vector <ll>
#define     PL              pair <ll,ll>
#define     vecp            vector < pair <ll, ll> >
#define     vecpp           vector < pair <ll, pair <ll, ll> > >
#define     se              set <ll>
#define     mapi            map<ll,ll>

#define     rep(i, l, r)        for(long long i = l; i<r; i++)
#define     repi(p, l, r, i)    for(long long p = l; p<r; p+=i)
#define     repb(i, r, l)       for(long long i = r; i>l; i--)
#define     repbd(p, r, l, d)   for(long long p = r; i>l; i-=d)

#define     max3(a, b, c)       max(a, max(b, c))
#define     max4(a, b, c, d)    max(max(a, b), max(c, d))
#define     min3(a, b, c)       min(a, min(b, c))
#define     min4(a, b, c, d)    min(min(a, b), min(c, d))

#define     vsort(v)            sort(v.begin(),v.end())
#define     all(container)      container.begin(), container.end()
#define     iterate(v, it)      for(vector< long long >::const_iterator it = v.begin(); it != v.end(); it++)

#define     BIG                 300000

using namespace std;

bool sortinrev(const pair<int,int> &a,
               const pair<int,int> &b)
{
       return (a.first > b.first);
}

int sumofdigits(string numinstring){
    int sum = 0;
    rep(i, 0, numinstring.size()){
        sum += numinstring[i] - '0' ;
    }
    return sum;
}

int checkDiffDigits(string str){
    for(int i = 0; i<str.size(); i++){
        for(int j = i+1; j<str.size();j++){
            if(str[i] == str[j]){
                return false;
                break;
            }
        }
    }
    return true;
}

/* Function to check if x is power of 2*/
bool isPowerOfTwo (long long x)
{
  /* First x in the below expression is
    for the case when x is 0 */
  return x && (!(x&(x-1)));
}

long long digitNO(long long num){
    return floor(log10(num)) + 1;
}

string converttostring(long long n){
    string s;
    stringstream ss;
    ss << n;
    s = ss.str();

    return s;
}

long long reversedigits(long long number){
    long long reverse = 0;
    long long rem;
    while(number!=0)
  {
     rem=number%10;
     reverse=reverse*10+rem;
     number/=10;
  }

  return reverse;
}

main(){
    int t; cin >> t;
    long long n;

    while (t--)
    {
        /* code */
        cin >> n;
        long long k = n-2;
        long long c = 0, one = 1;
        long long a[n];
        rep(i, 0, n){
            cin >> a[i];
        }
        sort(a, a+n);
        cout << min(a[n-2]-1, k);
    }

}


/////////////////////////////////////////////////////////////////////////////
//                                                                         //
//        * *       * * *     *   *       *     * * *     *         *      //
//      *     *   *       *   *   *       *   *       *   * *       *      //
//      *     *   *       *   *     *   *     *       *   *   *     *      //
//      * * *     * * * * *   *       *       * * * * *   *     *   *      //
//      * *       *       *   *       *       *       *   *       * *      //
//      *   *     *       *   *       *       *       *   *         *      //
//      *     *   *       *   *       *       *       *   *         *      //
//                                                                         //
/////////////////////////////////////////////////////////////////////////////

#include <bits/stdc++.h>
#include <cstdlib>
#include <cmath>
#include <stdio.h>
#include <math.h>

#define     fRead           freopen("input.txt","r",stdin)
#define     fWrite          freopen("output.txt","w",stdout)
#define     fast            ios_base::sync_with_stdio(false);cin.tie(NULL)

#define     ll              long long int
#define     ul              unsigned long long int
#define     dl              double
#define     st              string

#define     pb              push_back
#define     po              pop_back

#define     nl              endl
#define     rt              return 0

#define     N               cout << "No" << endl
#define     Y               cout << "Yes" << endl

#define     gcd(a, b)       __gcd(a, b)
#define     lcm(a, b)       (a * b) / gcd(a, b)

#define     all(v)          v.begin(),v.end()
#define     mem(a,v)        memset(a,v,sizeof(a))
#define     mod             1000000007
#define     mp              make_pair
#define     ins             insert
#define     rev             reverse
#define     _max            *max_element
#define     _min            *min_element
#define     SUM             accumulate
#define     BS              binary_search

#define     vec             vector <ll>
#define     PL              pair <ll,ll>
#define     vecp            vector < pair <ll, ll> >
#define     vecpp           vector < pair <ll, pair <ll, ll> > >
#define     se              set <ll>
#define     mapi            map<ll,ll>

#define     rep(i, l, r)        for(long long i = l; i<r; i++)
#define     repi(p, l, r, i)    for(long long p = l; p<r; p+=i)
#define     repb(i, r, l)       for(long long i = r; i>l; i--)
#define     repbd(p, r, l, d)   for(long long p = r; i>l; i-=d)

#define     max3(a, b, c)       max(a, max(b, c))
#define     max4(a, b, c, d)    max(max(a, b), max(c, d))
#define     min3(a, b, c)       min(a, min(b, c))
#define     min4(a, b, c, d)    min(min(a, b), min(c, d))

#define     vsort(v)            sort(v.begin(),v.end())
#define     all(container)      container.begin(), container.end()
#define     iterate(v, it)      for(vector< long long >::const_iterator it = v.begin(); it != v.end(); it++)

#define     BIG                 300000

using namespace std;

bool sortinrev(const pair<int,int> &a,
               const pair<int,int> &b)
{
       return (a.first > b.first);
}

int sumofdigits(string numinstring){
    int sum = 0;
    rep(i, 0, numinstring.size()){
        sum += numinstring[i] - '0' ;
    }
    return sum;
}

int checkDiffDigits(string str){
    for(int i = 0; i<str.size(); i++){
        for(int j = i+1; j<str.size();j++){
            if(str[i] == str[j]){
                return false;
                break;
            }
        }
    }
    return true;
}

/* Function to check if x is power of 2*/
bool isPowerOfTwo (long long x)
{
  /* First x in the below expression is
    for the case when x is 0 */
  return x && (!(x&(x-1)));
}

long long digitNO(long long num){
    return floor(log10(num)) + 1;
}

string converttostring(long long n){
    string s;
    stringstream ss;
    ss << n;
    s = ss.str();

    return s;
}

long long reversedigits(long long number){
    long long reverse = 0;
    long long rem;
    while(number!=0)
  {
     rem=number%10;
     reverse=reverse*10+rem;
     number/=10;
  }

  return reverse;
}

main(){
    int t; cin >> t;
    long long n;

    while (t--)
    {
        /* code */
        cin >> n;
        long long k = n-2;
        long long c = 0, one = 1;
        long long a[n];
        rep(i, 0, n){
            cin >> a[i];
            if(a[i] >= k+1){
                c++;
            }
            if(a[i] < 1){
                one = 0;
            }
        }
        if(k<1) {
            cout << 0 << endl;
            continue;
        }
        if(c>=2) cout << k << endl;
        else cout << k-c << endl;
    }

}


/////////////////////////////////////////////////////////////////////////////
//                                                                         //
//        * *       * * *     *   *       *     * * *     *         *      //
//      *     *   *       *   *   *       *   *       *   * *       *      //
//      *     *   *       *   *     *   *     *       *   *   *     *      //
//      * * *     * * * * *   *       *       * * * * *   *     *   *      //
//      * *       *       *   *       *       *       *   *       * *      //
//      *   *     *       *   *       *       *       *   *         *      //
//      *     *   *       *   *       *       *       *   *         *      //
//                                                                         //
/////////////////////////////////////////////////////////////////////////////

#include <bits/stdc++.h>
#include <cstdlib>
#include <cmath>
#include <stdio.h>
#include <math.h>

#define     fRead           freopen("input.txt","r",stdin)
#define     fWrite          freopen("output.txt","w",stdout)
#define     fast            ios_base::sync_with_stdio(false);cin.tie(NULL)

#define     ll              long long int
#define     ul              unsigned long long int
#define     dl              double
#define     st              string

#define     pb              push_back
#define     po              pop_back

#define     nl              endl
#define     rt              return 0

#define     N               cout << "No" << endl
#define     Y               cout << "Yes" << endl

#define     gcd(a, b)       __gcd(a, b)
#define     lcm(a, b)       (a * b) / gcd(a, b)

#define     all(v)          v.begin(),v.end()
#define     mem(a,v)        memset(a,v,sizeof(a))
#define     mod             1000000007
#define     mp              make_pair
#define     ins             insert
#define     rev             reverse
#define     _max            *max_element
#define     _min            *min_element
#define     SUM             accumulate
#define     BS              binary_search

#define     vec             vector <ll>
#define     PL              pair <ll,ll>
#define     vecp            vector < pair <ll, ll> >
#define     vecpp           vector < pair <ll, pair <ll, ll> > >
#define     se              set <ll>
#define     mapi            map<ll,ll>

#define     rep(i, l, r)        for(long long i = l; i<r; i++)
#define     repi(p, l, r, i)    for(long long p = l; p<r; p+=i)
#define     repb(i, r, l)       for(long long i = r; i>l; i--)
#define     repbd(p, r, l, d)   for(long long p = r; i>l; i-=d)

#define     max3(a, b, c)       max(a, max(b, c))
#define     max4(a, b, c, d)    max(max(a, b), max(c, d))
#define     min3(a, b, c)       min(a, min(b, c))
#define     min4(a, b, c, d)    min(min(a, b), min(c, d))

#define     vsort(v)            sort(v.begin(),v.end())
#define     all(container)      container.begin(), container.end()
#define     iterate(v, it)      for(vector< long long >::const_iterator it = v.begin(); it != v.end(); it++)

#define     BIG                 300000

using namespace std;

bool sortinrev(const pair<int,int> &a,
               const pair<int,int> &b)
{
       return (a.first > b.first);
}

int sumofdigits(string numinstring){
    int sum = 0;
    rep(i, 0, numinstring.size()){
        sum += numinstring[i] - '0' ;
    }
    return sum;
}

int checkDiffDigits(string str){
    for(int i = 0; i<str.size(); i++){
        for(int j = i+1; j<str.size();j++){
            if(str[i] == str[j]){
                return false;
                break;
            }
        }
    }
    return true;
}

/* Function to check if x is power of 2*/
bool isPowerOfTwo (long long x)
{
  /* First x in the below expression is
    for the case when x is 0 */
  return x && (!(x&(x-1)));
}

long long digitNO(long long num){
    return floor(log10(num)) + 1;
}

string converttostring(long long n){
    string s;
    stringstream ss;
    ss << n;
    s = ss.str();

    return s;
}

long long reversedigits(long long number){
    long long reverse = 0;
    long long rem;
    while(number!=0)
  {
     rem=number%10;
     reverse=reverse*10+rem;
     number/=10;
  }

  return reverse;
}

main(){
    int t; cin >> t;
    long long n;

    while (t--)
    {
        /* code */
        cin >> n;
        long long k = n-2;
        long long c = 0, one = 1;
        long long a[n];
        rep(i, 0, n){
            cin >> a[i];
        }
        sort(a, a+n);
        cout << min(a[n-2]-1, k) << endl;
    }

}


/////////////////////////////////////////////////////////////////////////////
//                                                                         //
//        * *       * * *     *   *       *     * * *     *         *      //
//      *     *   *       *   *   *       *   *       *   * *       *      //
//      *     *   *       *   *     *   *     *       *   *   *     *      //
//      * * *     * * * * *   *       *       * * * * *   *     *   *      //
//      * *       *       *   *       *       *       *   *       * *      //
//      *   *     *       *   *       *       *       *   *         *      //
//      *     *   *       *   *       *       *       *   *         *      //
//                                                                         //
/////////////////////////////////////////////////////////////////////////////

#include <bits/stdc++.h>
#include <cstdlib>
#include <cmath>
#include <stdio.h>
#include <math.h>

#define     fRead           freopen("input.txt","r",stdin)
#define     fWrite          freopen("output.txt","w",stdout)
#define     fast            ios_base::sync_with_stdio(false);cin.tie(NULL)

#define     ll              long long int
#define     ul              unsigned long long int
#define     dl              double
#define     st              string

#define     pb              push_back
#define     po              pop_back

#define     nl              endl
#define     rt              return 0

#define     N               cout << "No" << endl
#define     Y               cout << "Yes" << endl

#define     gcd(a, b)       __gcd(a, b)
#define     lcm(a, b)       (a * b) / gcd(a, b)

#define     all(v)          v.begin(),v.end()
#define     mem(a,v)        memset(a,v,sizeof(a))
#define     mod             1000000007
#define     mp              make_pair
#define     ins             insert
#define     rev             reverse
#define     _max            *max_element
#define     _min            *min_element
#define     SUM             accumulate
#define     BS              binary_search

#define     vec             vector <ll>
#define     PL              pair <ll,ll>
#define     vecp            vector < pair <ll, ll> >
#define     vecpp           vector < pair <ll, pair <ll, ll> > >
#define     se              set <ll>
#define     mapi            map<ll,ll>

#define     rep(i, l, r)        for(long long i = l; i<r; i++)
#define     repi(p, l, r, i)    for(long long p = l; p<r; p+=i)
#define     repb(i, r, l)       for(long long i = r; i>l; i--)
#define     repbd(p, r, l, d)   for(long long p = r; i>l; i-=d)

#define     max3(a, b, c)       max(a, max(b, c))
#define     max4(a, b, c, d)    max(max(a, b), max(c, d))
#define     min3(a, b, c)       min(a, min(b, c))
#define     min4(a, b, c, d)    min(min(a, b), min(c, d))

#define     vsort(v)            sort(v.begin(),v.end())
#define     all(container)      container.begin(), container.end()
#define     iterate(v, it)      for(vector< long long >::const_iterator it = v.begin(); it != v.end(); it++)

#define     BIG                 300000

using namespace std;

bool sortinrev(const pair<int,int> &a,
               const pair<int,int> &b)
{
       return (a.first > b.first);
}

int sumofdigits(string numinstring){
    int sum = 0;
    rep(i, 0, numinstring.size()){
        sum += numinstring[i] - '0' ;
    }
    return sum;
}

int checkDiffDigits(string str){
    for(int i = 0; i<str.size(); i++){
        for(int j = i+1; j<str.size();j++){
            if(str[i] == str[j]){
                return false;
                break;
            }
        }
    }
    return true;
}

/* Function to check if x is power of 2*/
bool isPowerOfTwo (long long x)
{
  /* First x in the below expression is
    for the case when x is 0 */
  return x && (!(x&(x-1)));
}

long long digitNO(long long num){
    return floor(log10(num)) + 1;
}

string converttostring(long long n){
    string s;
    stringstream ss;
    ss << n;
    s = ss.str();

    return s;
}

long long reversedigits(long long number){
    long long reverse = 0;
    long long rem;
    while(number!=0)
  {
     rem=number%10;
     reverse=reverse*10+rem;
     number/=10;
  }

  return reverse;
}

main(){
    int t; cin >> t;
    long long n;

    while (t--)
    {
        /* code */
        cin >> n;
        long long k = n-2;
        if(k<1) {
            cout << 0 << endl;
            continue;
        }
        long long c = 0, one = 1;
        long long a[n];
        rep(i, 0, n){
            cin >> a[i];
            if(a[i] >= k+1){
                c++;
            }
            if(a[i] < 1){
                one = 0;
            }
        }
        if(c>=2) cout << k << endl;
        else cout << k-c << endl;
    }

}


/////////////////////////////////////////////////////////////////////////////
//                                                                         //
//        * *       * * *     *   *       *     * * *     *         *      //
//      *     *   *       *   *   *       *   *       *   * *       *      //
//      *     *   *       *   *     *   *     *       *   *   *     *      //
//      * * *     * * * * *   *       *       * * * * *   *     *   *      //
//      * *       *       *   *       *       *       *   *       * *      //
//      *   *     *       *   *       *       *       *   *         *      //
//      *     *   *       *   *       *       *       *   *         *      //
//                                                                         //
/////////////////////////////////////////////////////////////////////////////

#include <bits/stdc++.h>
#include <cstdlib>
#include <cmath>
#include <stdio.h>
#include <math.h>

#define     fRead           freopen("input.txt","r",stdin)
#define     fWrite          freopen("output.txt","w",stdout)
#define     fast            ios_base::sync_with_stdio(false);cin.tie(NULL)

#define     ll              long long int
#define     ul              unsigned long long int
#define     dl              double
#define     st              string

#define     pb              push_back
#define     po              pop_back

#define     nl              endl
#define     rt              return 0

#define     N               cout << "No" << endl
#define     Y               cout << "Yes" << endl

#define     gcd(a, b)       __gcd(a, b)
#define     lcm(a, b)       (a * b) / gcd(a, b)

#define     all(v)          v.begin(),v.end()
#define     mem(a,v)        memset(a,v,sizeof(a))
#define     mod             1000000007
#define     mp              make_pair
#define     ins             insert
#define     rev             reverse
#define     _max            *max_element
#define     _min            *min_element
#define     SUM             accumulate
#define     BS              binary_search

#define     vec             vector <ll>
#define     PL              pair <ll,ll>
#define     vecp            vector < pair <ll, ll> >
#define     vecpp           vector < pair <ll, pair <ll, ll> > >
#define     se              set <ll>
#define     mapi            map<ll,ll>

#define     rep(i, l, r)        for(long long i = l; i<r; i++)
#define     repi(p, l, r, i)    for(long long p = l; p<r; p+=i)
#define     repb(i, r, l)       for(long long i = r; i>l; i--)
#define     repbd(p, r, l, d)   for(long long p = r; i>l; i-=d)

#define     max3(a, b, c)       max(a, max(b, c))
#define     max4(a, b, c, d)    max(max(a, b), max(c, d))
#define     min3(a, b, c)       min(a, min(b, c))
#define     min4(a, b, c, d)    min(min(a, b), min(c, d))

#define     vsort(v)            sort(v.begin(),v.end())
#define     all(container)      container.begin(), container.end()
#define     iterate(v, it)      for(vector< long long >::const_iterator it = v.begin(); it != v.end(); it++)

#define     BIG                 300000

using namespace std;

bool sortinrev(const pair<int,int> &a,
               const pair<int,int> &b)
{
       return (a.first > b.first);
}

int sumofdigits(string numinstring){
    int sum = 0;
    rep(i, 0, numinstring.size()){
        sum += numinstring[i] - '0' ;
    }
    return sum;
}

int checkDiffDigits(string str){
    for(int i = 0; i<str.size(); i++){
        for(int j = i+1; j<str.size();j++){
            if(str[i] == str[j]){
                return false;
                break;
            }
        }
    }
    return true;
}

/* Function to check if x is power of 2*/
bool isPowerOfTwo (long long x)
{
  /* First x in the below expression is
    for the case when x is 0 */
  return x && (!(x&(x-1)));
}

long long digitNO(long long num){
    return floor(log10(num)) + 1;
}

string converttostring(long long n){
    string s;
    stringstream ss;
    ss << n;
    s = ss.str();

    return s;
}

long long reversedigits(long long number){
    long long reverse = 0;
    long long rem;
    while(number!=0)
  {
     rem=number%10;
     reverse=reverse*10+rem;
     number/=10;
  }

  return reverse;
}

main(){
    int t; cin >> t;
    long long n;

    while (t--)
    {
        /* code */
        cin >> n;
        long long k = n-2;
        long long c = 0, one = 1;
        long long a[n];
        rep(i, 0, n){
            cin >> a[i];
            if(a[i] >= k+1){
                c++;
            }
            if(a[i] < 1){
                one = 0;
            }
        }
        if(k<1) {
            cout << 0 << endl;
            continue;
        }
        if(c>=2) cout << k << endl;
        else cout << n-k-c << endl;
    }

}


/////////////////////////////////////////////////////////////////////////////
//                                                                         //
//        * *       * * *     *   *       *     * * *     *         *      //
//      *     *   *       *   *   *       *   *       *   * *       *      //
//      *     *   *       *   *     *   *     *       *   *   *     *      //
//      * * *     * * * * *   *       *       * * * * *   *     *   *      //
//      * *       *       *   *       *       *       *   *       * *      //
//      *   *     *       *   *       *       *       *   *         *      //
//      *     *   *       *   *       *       *       *   *         *      //
//                                                                         //
/////////////////////////////////////////////////////////////////////////////

#include <bits/stdc++.h>
#include <cstdlib>
#include <cmath>
#include <stdio.h>
#include <math.h>

#define     fRead           freopen("input.txt","r",stdin)
#define     fWrite          freopen("output.txt","w",stdout)
#define     fast            ios_base::sync_with_stdio(false);cin.tie(NULL)

#define     ll              long long int
#define     ul              unsigned long long int
#define     dl              double
#define     st              string

#define     pb              push_back
#define     po              pop_back

#define     nl              endl
#define     rt              return 0

#define     N               cout << "No" << endl
#define     Y               cout << "Yes" << endl

#define     gcd(a, b)       __gcd(a, b)
#define     lcm(a, b)       (a * b) / gcd(a, b)

#define     all(v)          v.begin(),v.end()
#define     mem(a,v)        memset(a,v,sizeof(a))
#define     mod             1000000007
#define     mp              make_pair
#define     ins             insert
#define     rev             reverse
#define     _max            *max_element
#define     _min            *min_element
#define     SUM             accumulate
#define     BS              binary_search

#define     vec             vector <ll>
#define     PL              pair <ll,ll>
#define     vecp            vector < pair <ll, ll> >
#define     vecpp           vector < pair <ll, pair <ll, ll> > >
#define     se              set <ll>
#define     mapi            map<ll,ll>

#define     rep(i, l, r)        for(long long i = l; i<r; i++)
#define     repi(p, l, r, i)    for(long long p = l; p<r; p+=i)
#define     repb(i, r, l)       for(long long i = r; i>l; i--)
#define     repbd(p, r, l, d)   for(long long p = r; i>l; i-=d)

#define     max3(a, b, c)       max(a, max(b, c))
#define     max4(a, b, c, d)    max(max(a, b), max(c, d))
#define     min3(a, b, c)       min(a, min(b, c))
#define     min4(a, b, c, d)    min(min(a, b), min(c, d))

#define     vsort(v)            sort(v.begin(),v.end())
#define     all(container)      container.begin(), container.end()
#define     iterate(v, it)      for(vector< long long >::const_iterator it = v.begin(); it != v.end(); it++)

#define     BIG                 300000

using namespace std;

bool sortinrev(const pair<int,int> &a,
               const pair<int,int> &b)
{
       return (a.first > b.first);
}

int sumofdigits(string numinstring){
    int sum = 0;
    rep(i, 0, numinstring.size()){
        sum += numinstring[i] - '0' ;
    }
    return sum;
}

int checkDiffDigits(string str){
    for(int i = 0; i<str.size(); i++){
        for(int j = i+1; j<str.size();j++){
            if(str[i] == str[j]){
                return false;
                break;
            }
        }
    }
    return true;
}

/* Function to check if x is power of 2*/
bool isPowerOfTwo (long long x)
{
  /* First x in the below expression is
    for the case when x is 0 */
  return x && (!(x&(x-1)));
}

long long digitNO(long long num){
    return floor(log10(num)) + 1;
}

string converttostring(long long n){
    string s;
    stringstream ss;
    ss << n;
    s = ss.str();

    return s;
}

long long reversedigits(long long number){
    long long reverse = 0;
    long long rem;
    while(number!=0)
  {
     rem=number%10;
     reverse=reverse*10+rem;
     number/=10;
  }

  return reverse;
}

main(){
    int t; cin >> t;
    long long n;

    while (t--)
    {
        /* code */
        cin >> n;
        long long k = n-2;
        long long c = 0, one = 1;
        long long a[n];
        rep(i, 0, n){
            cin >> a[i];
            if(a[i] >= k+1){
                c++;
            }
            if(a[i] < 1){
                one = 0;
            }
        }
        if(k<1) {
            cout << 0 << endl;
            continue;
        }
        if(c>=2) cout << k << endl;
        else cout << min(k-c, n-k-c) << endl;
    }

}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    long long int t;
    cin>>t;
    while(t--)
    {
        long long int n;
        cin>>n;
        long long int a[n];
        for(int i=0;i<n;i++)
        cin>>a[i];
        sort(a,a+n);
        long long int mi=min(a[n-1],a[n-2]);
        long long int m=0;
        for(int i=1;i<n-2;i++)
        {
            m++;
            if(m<mi)
            continue;
            else
            {
                m--;
                break;
            }
        }
        cout<<m<<"\n";
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    long long int t;
    cin>>t;
    while(t--)
    {
        long long int n;
        cin>>n;
        long long int a[n];
        for(int i=0;i<n;i++)
        cin>>a[i];
        sort(a,a+n);
        long long int mi=min(a[n-1],a[n-2]);
        long long int m=0;
        for(int i=0;i<n-2;i++)
        {
            m++;
            if(m<mi)
            continue;
            else
            {
                m--;
                break;
            }
        }
        cout<<m<<"\n";
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    long long int t;
    cin>>t;
    while(t--)
    {
        long long int n;
        cin>>n;
        long long int a[n];
        for(int i=0;i<n;i++)
        cin>>a[i];
        sort(a,a+n);
        long long int m=0,c=1;
        for(int i=1;i<n;i++)
        {
            if(a[i]==a[i-1])
            c++;
            else
            {
                if(n-c>=2)
                { long long int mi=min(c,n-c);
                  m=max(mi,m);
                }
                c=1;
            }
        }
        cout<<m<<"\n";
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    long long int t;
    cin>>t;
    while(t--)
    {
        long long int n;
        cin>>n;
        long long int a[n];
        for(int i=0;i<n;i++)
        cin>>a[i];
        sort(a,a+n);
        long long int m=0,c=1,l=n;
        for(int i=1;i<n;i++)
        {
            if(a[i]==a[i-1])
            c++;
            else
            {
                if(l-c>=2)
                { long long int mi=min(c,l-c);
                  m=max(mi,m);
                }
                l=l-c;
                c=1;
            }
        }
        cout<<m<<"\n";
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    long long int t;
    cin>>t;
    while(t--)
    {
        long long int n;
        cin>>n;
        long long int a[n];
        for(int i=0;i<n;i++)
        cin>>a[i];
        sort(a,a+n);
        long long int m=0,c=1,pos=0;
        for(int i=1;i<n;i++)
        {
            if(a[i]==a[i-1])
            c++;
            else
            {
                if(n-c>=2)
                { long long int mi=min(c,n-c);
                  m=max(mi,m);
                }
            }
        }
        cout<<m<<"\n";
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    long long int t;
    cin>>t;
    while(t--)
    {
        long long int n;
        cin>>n;
        long long int a[n];
        for(int i=0;i<n;i++)
        cin>>a[i];
        sort(a,a+n);
        long long int m=0,c=1;
        for(int i=1;i<n;i++)
        {
            if(a[i]==a[i-1])
            c++;
            else
            {
                if(n-c>=2)
                m=max(c,m);
                c=1;
            }
        }
        cout<<m<<"\n";
    }
    return 0;
}


/*
    ************

    Author : avi

    ************
*/
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define st string
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define pp pair<ll,ll>a
struct trp{
    int x,y,z;
};
#define IO ios_base::sync_with_stdio(false); cin.tie(NULL)
#define test ll t; cin>>t

void fun()
{
     #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
}
int main()
{

    IO;
    test;
    while(t--)
    {
        ll n;
        cin>>n;
        ll a[n];
        for(ll i=0;i<n;i++) cin>>a[i];
        sort(a,a+n);
        ll x=a[n-2];
        ll c=0;
        for(ll i=0;i<n;i++)
        {
            if(a[i]<x)
                c++;
        }
        cout << min(c,x) << endl;
    }

}


/*
    ************

    Author : avi

    ************
*/
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define st string
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define pp pair<ll,ll>a
struct trp{
    int x,y,z;
};
#define IO ios_base::sync_with_stdio(false); cin.tie(NULL)
#define test ll t; cin>>t

void fun()
{
     #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
}
int main()
{

    IO;
    test;
    while(t--)
    {
        ll n;
        cin>>n;
        ll a[n];
        for(ll i=0;i<n;i++) cin>>a[i];
        sort(a,a+n);
        ll x=a[n-2];
        ll c=0;
        for(ll i=0;i<n;i++)
        {
            if(a[i]<x)
                c++;
        }
        if(c>=x)
        {
            c=x-1;
        }
        cout << min(c,x) << endl;
    }

}


/*
    ************

    Author : avi

    ************
*/
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define st string
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define pp pair<ll,ll>a
struct trp{
    int x,y,z;
};
#define IO ios_base::sync_with_stdio(false); cin.tie(NULL)
#define test ll t; cin>>t

void fun()
{
     #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
}
int main()
{

    IO;
    test;
    while(t--)
    {
        ll n;
        cin>>n;
        ll a[n];
        for(ll i=0;i<n;i++) cin>>a[i];
        sort(a,a+n);
        ll x=a[n-2];
        ll c=0;
        for(ll i=0;i<n-2;i++)
        {

                c++;
        }
        if(c>=x)
        {
            c=x-1;
        }
        cout << min(c,x) << endl;
    }

}


/*
    ************

    Author : avi

    ************
*/
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define st string
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define pp pair<ll,ll>a
struct trp{
    int x,y,z;
};
#define IO ios_base::sync_with_stdio(false); cin.tie(NULL)
#define test ll t; cin>>t

void fun()
{
     #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
}
int main()
{

    IO;
    test;
    while(t--)
    {
        ll n;
        cin>>n;
        ll a[n];
        for(ll i=0;i<n;i++) cin>>a[i];
        sort(a,a+n);
        ll x=a[n-2];
        ll c=0;
        for(ll i=0;i<n;i++)
        {
            if(a[i]<x)
                c++;
        }
        cout << c << endl;
    }

}


/*
    ************

    Author : avi

    ************
*/
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define st string
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define pp pair<ll,ll>a
struct trp{
    int x,y,z;
};
#define IO ios_base::sync_with_stdio(false); cin.tie(NULL)
#define test ll t; cin>>t

void fun()
{
     #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
}
int main()
{

    IO;
   // test;

        ll n;
        cin>>n;
        ll a[n];
        for(ll i=0;i<n;i++) cin>>a[i];
        ll f=1;
         ll i=0;
        for(;i<n-1;i++)
        {
            if(a[i]<a[i+1])
                continue;
            else
                break;

        }
        for(;i<n-1;i++)
        {
            if(a[i]<a[i+1])
            {
                f=0;
                break;
            }
        }
        if(f)
            cout << "YES";
        else
            cout << "NO";

}


#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
const int maxn=1e6+10;
int T,n,k,a[maxn],num[maxn],sum,now;
int main()
{
	scanf("%d",&T);
	while (T--)
	{
		scanf("%d",&n); int ans=0,lc=-1;
		for (int i=1;i<=n;i++) scanf("%d",&a[i]),num[a[i]]++;
		for (int i=100000;i>=2;i--) if (num[i]>=2) {lc=i; break;}
		int ma=-1;
		for (int i=1;i<=lc-1;i++) ma=max(ma,num[i]);
		if (ma!=-1) ans=min(ma,lc-1);
		for (int i=1;i<=n;i++) num[a[i]]=0;
		printf("%d\n",ans);
	}
return 0;
}


#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
const int maxn=1e6+10;
int T,n,k,a[maxn],num[maxn],sum,now;
int main()
{
	scanf("%d",&T);
	while (T--)
	{
		scanf("%d",&n); int ans=0,lc=-1;
		for (int i=1;i<=n;i++) scanf("%d",&a[i]),num[a[i]]++;
		for (int i=100000;i>=2;i--) if (num[i]>=2) {lc=i; break;}
		int ma=-1;
		for (int i=1;i<=lc-1;i++) ma=max(ma,num[i]);
		if (ma!=-1) ans=ma;
		for (int i=1;i<=n;i++) num[a[i]]=0;
		printf("%d\n",ans);
	}
return 0;
}


#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
const int maxn=1e6+10;
int T,n,k,a[maxn],num[maxn],pre[maxn],nt[maxn];
int main()
{
	scanf("%d",&T);
	while (T--)
	{
		scanf("%d",&n); int ans=0;
		for (int i=0;i<=100000+10;i++) pre[i]=nt[i]=num[i]=0;
		for (int i=1;i<=n;i++) scanf("%d",&a[i]),num[a[i]]++;
		for (int i=1;i<=100000;i++) pre[i]=max(pre[i-1],num[i]);
		for (int i=100000;i>=1;i--) nt[i]=max(nt[i+1],num[i]);
		for (int i=2;i<=100000;i++)
		if (num[i]>=2)
		{
			int ma=max(num[i]-2,max(pre[i-1],nt[i+1]));
			//if (i==2) printf("lalala %d\n",ma);
			ans=max(ans,min(i-1,ma));
		}
		printf("%d\n",ans);
	}
return 0;
}


#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
const int maxn=1e6+10;
int T,n,k,a[maxn],num[maxn],sum,now;
int main()
{
	scanf("%d",&T);
	while (T--)
	{
		scanf("%d",&n); int ans=0,lc=-1;
		for (int i=1;i<=n;i++) scanf("%d",&a[i]),num[a[i]]++;
		for (int i=100000;i>=2;i--) if (num[i]>=2) {lc=i; num[i]-=2; break;}
		int ma=-1;
		for (int i=1;i<=100000;i++) ma=max(ma,num[i]);
		if (ma!=-1 && lc!=-1) ans=min(ma,lc-1);
		for (int i=1;i<=n;i++) num[a[i]]=0;
		printf("%d\n",ans);
	}
return 0;
}


#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
const int maxn=1e6+10;
int T,n,k,a[maxn],num[maxn],pre[maxn],nt[maxn];
int main()
{
	scanf("%d",&T);
	while (T--)
	{
		scanf("%d",&n); int ans=0,d=2,ma;
		for (int i=0;i<=100000+10;i++) num[i]=0;
		for (int i=1;i<=n;i++) scanf("%d",&a[i]),num[a[i]]++;
		for (int i=100000;i>1;i--)
		if (num[i])
		{
			while (num[i] && d) {num[i]--; d--;}
			if (!d) {ma=i-1; break;}
		}
		if (!d) ans=min(ma,n-2);
		printf("%d\n",ans);
	}
return 0;
}


#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
const int maxn=1e6+10;
int T,n,k,a[maxn],num[maxn],sum,now;
int main()
{
	scanf("%d",&T);
	while (T--)
	{
		scanf("%d",&n); int ans=0; sum=0;
		for (int i=1;i<=n;i++) scanf("%d",&a[i]),num[a[i]]++;
		sum+=num[1];
		for (int i=2;i<=100000;i++)
		{
			if (n-sum>=2) ans=min(i-1,sum);
			sum+=num[i];
		}
		for (int i=1;i<=n;i++) num[a[i]]=0;
		printf("%d\n",ans);
	}
return 0;
}


#include<bits/stdc++.h>
using namespace std;
///Welcome to Nasif's Code
#define co(q) cout<<q<<endl;
typedef long long int ll;
typedef unsigned long long int ull;
const int MOD = (int)1e9+7;
const int MAX = 1e6;
#define pi acos(-1)
#define bug cout<<"bug"<<endl;
#define FastRead     ios_base::sync_with_stdio(false);cin.tie(NULL);

int arr[200005];
int main()
{
//freopen("output.txt", "w", stdout);

    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        for(int i=0; i<n; i++)
            cin>>arr[i];
        sort(arr,arr+n);
        ll l=arr[n-1],r=arr[n-2];
        ll taken=0;
        for(ll i=n-2; i>0; i--)
        {
            ll pos=min(l,r);
            pos--;
            taken=max(taken,min(pos,i));
            if(l<r)
                l+=arr[i-1];
            else
                r+=arr[i-1];
        }
        cout<<taken<<endl;

    }

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
///Welcome to Nasif's Code
#define co(q) cout<<q<<endl;
typedef long long int ll;
typedef unsigned long long int ull;
const int MOD = (int)1e9+7;
const int MAX = 1e6;
#define pi acos(-1)
#define bug cout<<"bug"<<endl;
#define FastRead     ios_base::sync_with_stdio(false);cin.tie(NULL);

int arr[100005];
int main()
{
//freopen("output.txt", "w", stdout);

    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        for(int i=0; i<n; i++)
            cin>>arr[i];
        sort(arr,arr+n);
        int l=arr[n-1],r=arr[n-2];
        int lim=n-2;
        int taken=0;
        while(lim--)
        {
            int pos=min(l,r);
            pos--;
            taken=max(taken,min(pos,lim+1));
            if(l<r)
                l+=arr[lim-1]-1;
            else
                r+=arr[lim-1]-1;
        }
        cout<<taken<<endl;

    }

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
///Welcome to Nasif's Code
#define co(q) cout<<q<<endl;
typedef long long int ll;
typedef unsigned long long int ull;
const int MOD = (int)1e9+7;
const int MAX = 1e6;
#define pi acos(-1)
#define bug cout<<"bug"<<endl;
#define FastRead     ios_base::sync_with_stdio(false);cin.tie(NULL);

int arr[100005];
int main()
{
//freopen("output.txt", "w", stdout);

    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        for(int i=0; i<n; i++)
            cin>>arr[i];
        sort(arr,arr+n);
        int l=arr[n-1],r=arr[n-2];
        int lim=n-2;
        int taken=0;
        while(lim--)
        {
            int pos=min(l,r);
            pos--;
            taken=max(taken,min(pos,lim+1));
            if(l<r)
                l+=arr[lim-1];
            else
                r+=arr[lim-1];
        }
        cout<<taken<<endl;

    }

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
///Welcome to Nasif's Code
#define co(q) cout<<q<<endl;
typedef long long int ll;
typedef unsigned long long int ull;
const int MOD = (int)1e9+7;
const int MAX = 1e6;
#define pi acos(-1)
#define bug cout<<"bug"<<endl;
#define FastRead     ios_base::sync_with_stdio(false);cin.tie(NULL);

int arr[100005];
int main()
{
//freopen("output.txt", "w", stdout);

    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        for(int i=0; i<n; i++)
            cin>>arr[i];
        sort(arr,arr+n);
        int l=arr[n-1],r=arr[n-2];
        int k=min(l,r);
        k--;
        n-=2;
        cout<<min(k,n)<<endl;
    }

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
///Welcome to Nasif's Code
#define co(q) cout<<q<<endl;
typedef long long int ll;
typedef unsigned long long int ull;
const int MOD = (int)1e9+7;
const int MAX = 1e6;
#define pi acos(-1)
#define bug cout<<"bug"<<endl;
#define FastRead     ios_base::sync_with_stdio(false);cin.tie(NULL);

int arr[100005];
int main()
{
//freopen("output.txt", "w", stdout);

    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        for(int i=0; i<n; i++)
            cin>>arr[i];
        sort(arr,arr+n);
        int l=arr[n-1],r=arr[n-2];
        int lim=n-2;
        int taken=0;
        while(lim--)
        {
            int pos=min(l,r);
            pos--;
            taken=max(taken,min(pos,lim+1));
            if(l<r)
                l+=arr[lim]-1;
            else
                r+=arr[lim]-1;
        }
        cout<<taken<<endl;

    }

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
///Welcome to Nasif's Code
#define co(q) cout<<q<<endl;
typedef long long int ll;
typedef unsigned long long int ull;
const int MOD = (int)1e9+7;
const int MAX = 1e6;
#define pi acos(-1)
#define bug cout<<"bug"<<endl;
#define FastRead     ios_base::sync_with_stdio(false);cin.tie(NULL);

int arr[100005];
int main()
{
//freopen("output.txt", "w", stdout);

    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        for(int i=0; i<n; i++)
            cin>>arr[i];
        sort(arr,arr+n);
        ll l=arr[n-1],r=arr[n-2];
        ll lim=n-2;
        ll taken=0;
        while(lim--)
        {
            ll pos=min(l,r);
            pos--;
            taken=max(taken,min(pos,lim+1));
            if(l<r)
                l+=arr[lim-1];
            else
                r+=arr[lim-1];
        }
        cout<<taken<<endl;

    }

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
///Welcome to Nasif's Code
#define co(q) cout<<q<<endl;
typedef long long int ll;
typedef unsigned long long int ull;
const int MOD = (int)1e9+7;
const int MAX = 1e6;
#define pi acos(-1)
#define bug cout<<"bug"<<endl;
#define FastRead     ios_base::sync_with_stdio(false);cin.tie(NULL);

int arr[100005];
int main()
{
//freopen("output.txt", "w", stdout);

    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        for(int i=0; i<n; i++)
            cin>>arr[i];
        sort(arr,arr+n);
        int l=arr[n-1],r=arr[n-2];
        int lim=n-2;
        int taken=0;
        while(taken<lim)
        {
            int k=min(l,r);
            k--;
            taken++;
            if(taken>k){
                taken--;
                if(l<r)
                    l+=arr[lim-1];
                else
                    r+=arr[lim-1];
                lim--;
            }
        }
        cout<<taken<<endl;

    }

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
///Welcome to Nasif's Code
#define co(q) cout<<q<<endl;
typedef long long int ll;
typedef unsigned long long int ull;
const int MOD = (int)1e9+7;
const int MAX = 1e6;
#define pi acos(-1)
#define bug cout<<"bug"<<endl;
#define FastRead     ios_base::sync_with_stdio(false);cin.tie(NULL);

int arr[100005];
int main()
{
//freopen("output.txt", "w", stdout);

    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        for(int i=0; i<n; i++)
            cin>>arr[i];
        sort(arr,arr+n);
        int l=arr[n-1],r=arr[n-2];
        int lim=n-2;
        int taken=0;
        while(lim--)
        {
            int pos=min(l,r);
            pos--;
            taken=max(taken,min(pos,lim+1));
            if(l<r)
                l+=arr[lim];
            else
                r+=arr[lim];
        }
        cout<<taken<<endl;

    }

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
///Welcome to Nasif's Code
#define co(q) cout<<q<<endl;
typedef long long int ll;
typedef unsigned long long int ull;
const int MOD = (int)1e9+7;
const int MAX = 1e6;
#define pi acos(-1)
#define bug cout<<"bug"<<endl;
#define FastRead     ios_base::sync_with_stdio(false);cin.tie(NULL);

int arr[100005];
int main()
{
//freopen("output.txt", "w", stdout);

    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        for(int i=0; i<n; i++)
            cin>>arr[i];
        sort(arr,arr+n);
        int l=arr[n-1],r=arr[n-2];
        int lim=n-2;
        if(l==1 || r==1)
        {
            cout<<"0"<<endl;
           continue;
        }
        int taken=0;
        while(lim--)
        {
            int pos=min(l,r);
            pos--;
            taken=max(taken,min(pos,lim+1));
           // cout<<pos<<" "<<taken<<endl;
            if(l<r)
                l+=arr[lim];
            else
                r+=arr[lim];
        }
        cout<<taken<<endl;

    }

    return 0;
}


#include<bits/stdc++.h>
#define ll long long int
#define MAX 1000003
#define pii pair<ll,ll>
#define VP vector< pii >
#define MOD 1000000007
#define mp make_pair
#define pb push_back
#define rep(i,a,b) for(ll (i) = (a); (i) < (b); (i)++)
#define all(v) (v).begin(),(v).end()
#define S(x) scanf("%d",&(x))
#define S2(x,y) scanf("%d%d",&(x),&(y))
#define SL(x) scanf("%lld",&(x))
#define SL2(x) scanf("%lld%lld",&(x),&(y))
#define P(x) printf("%d\n",(x))
#define FF first
#define SS second
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll t;
cin>>t;
while(t--)
{
	ll n;
	cin>>n;
	vector<ll>v(n);
	unordered_map<ll,ll>cnt;
	rep(i,0,n){
		cin>>v[i];
		cnt[v[i]]++;
	}
	sort(all(v));
	ll base=min(v[n-1],v[n-2]);
	ll ans=0;
	rep(i,1,n-1)
		{
			ll steps=0;
			rep(j,0,n-2)
				{
					if(v[j]<base)
							{
								steps++;
							}
					if(steps==i)
							{
								ans=max(ans,steps);
								break;
							}
				}
		}
	cout<<ans<<endl;
}

return 0;
}


#include<bits/stdc++.h>
#define ll long long int
#define MAX 1000003
#define pii pair<ll,ll>
#define VP vector< pii >
#define MOD 1000000007
#define mp make_pair
#define pb push_back
#define rep(i,a,b) for(ll (i) = (a); (i) < (b); (i)++)
#define all(v) (v).begin(),(v).end()
#define S(x) scanf("%d",&(x))
#define S2(x,y) scanf("%d%d",&(x),&(y))
#define SL(x) scanf("%lld",&(x))
#define SL2(x) scanf("%lld%lld",&(x),&(y))
#define P(x) printf("%d\n",(x))
#define FF first
#define SS second
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll t;
cin>>t;
while(t--)
{
	ll n;
	cin>>n;
	vector<ll>v(n);
	rep(i,0,n)
		cin>>v[i];
	sort(all(v));
	ll base=min(v[n-1],v[n-2]);
	ll steps=0;
	rep(i,0,n-2)
		{
			if(v[i]>=1 && steps<base && v[i]<base)
					{
						steps++;
					}
		}
	cout<<steps<<endl;
}
return 0;
}


#include<bits/stdc++.h>
#define ll long long int
#define MAX 1000003
#define pii pair<ll,ll>
#define VP vector< pii >
#define MOD 1000000007
#define mp make_pair
#define pb push_back
#define rep(i,a,b) for(ll (i) = (a); (i) < (b); (i)++)
#define all(v) (v).begin(),(v).end()
#define S(x) scanf("%d",&(x))
#define S2(x,y) scanf("%d%d",&(x),&(y))
#define SL(x) scanf("%lld",&(x))
#define SL2(x) scanf("%lld%lld",&(x),&(y))
#define P(x) printf("%d\n",(x))
#define FF first
#define SS second
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll t;
cin>>t;
while(t--)
{
	ll n;
	cin>>n;
	vector<ll>v(n);
	rep(i,0,n){
		cin>>v[i];
	}
	sort(all(v));
	ll base=min(v[n-1],v[n-2]);
	ll ans=min(base-1,n-2);
	cout<<ans<<endl;
}

return 0;
}


#include<bits/stdc++.h>
#define ll long long int
#define MAX 1000003
#define pii pair<ll,ll>
#define VP vector< pii >
#define MOD 1000000007
#define mp make_pair
#define pb push_back
#define rep(i,a,b) for(ll (i) = (a); (i) < (b); (i)++)
#define all(v) (v).begin(),(v).end()
#define S(x) scanf("%d",&(x))
#define S2(x,y) scanf("%d%d",&(x),&(y))
#define SL(x) scanf("%lld",&(x))
#define SL2(x) scanf("%lld%lld",&(x),&(y))
#define P(x) printf("%d\n",(x))
#define FF first
#define SS second
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll t;
cin>>t;
while(t--)
{
	ll n;
	cin>>n;
	vector<ll>v(n);
	rep(i,0,n)
		cin>>v[i];
	sort(all(v));
	ll steps=0;
	for(ll k=n-2;k>=0;k--)
			{
				ll base=v[n-2];
				ll steps=0;
				rep(i,0,k)
					{
						if(v[i]<base)
								{
									steps++;
								}
					}
				if(steps==k)
						{
							cout<<steps<<endl;
							break;
						}
			}
}
return 0;
}


#include<bits/stdc++.h>
#define ll long long int
#define MAX 1000003
#define pii pair<ll,ll>
#define VP vector< pii >
#define MOD 1000000007
#define mp make_pair
#define pb push_back
#define rep(i,a,b) for(ll (i) = (a); (i) < (b); (i)++)
#define all(v) (v).begin(),(v).end()
#define S(x) scanf("%d",&(x))
#define S2(x,y) scanf("%d%d",&(x),&(y))
#define SL(x) scanf("%lld",&(x))
#define SL2(x) scanf("%lld%lld",&(x),&(y))
#define P(x) printf("%d\n",(x))
#define FF first
#define SS second
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll t;
cin>>t;
while(t--)
{
	ll n;
	cin>>n;
	vector<ll>v(n);
	unordered_map<ll,ll>cnt;
	rep(i,0,n){
		cin>>v[i];
		cnt[v[i]]++;
	}
	sort(all(v));
	ll ans=0;
	for(ll k=n-2;k>=0;k--)
			{
				ll base=v[n-2];
				ll steps=0;
				rep(i,0,k)
					{
						if(v[i]>=1 && v[i]<base)
								{
									steps++;
								}
					}
				ans=max(min(k,steps),ans);

			}
	cout<<ans<<endl;
}

return 0;
}