Untitled

mail@pastecode.io avatar
unknown
plain_text
21 days ago
1.6 kB
0
Indexable
Never
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define endl "\n"
 
const double PI = 3.14159265358979;
const ll INF =  1e9 + 7;
const ll MOD = 1e9 + 7;
const ll nax = 100005;
const int LOG = 25;


int freq[nax];

class Solution {
public:
    void solve() {
        int n, totalDistinct = 0;
        cin >> n;
        int a[n];

        for (int i = 0; i < n; i++) {
            cin >> a[i];
            freq[a[i]]++;
            if (freq[a[i]] == 1) {
                totalDistinct++;
            }
        }

        for (int i = 0; i < n; i++) {
            freq[a[i]] = 0;
        }

        int tail = 0, head = tail - 1, currDistinct = 0, ans = n;
        
        while(tail < n) {
            while(head + 1 < n && currDistinct < totalDistinct) {
                head++;
                freq[a[head]]++;
                if (freq[a[head]] == 1) {
                    currDistinct++;
                }
            }

            if (currDistinct == totalDistinct) {
                ans = min(ans, head - tail + 1);
            }

            if (head >= tail) {
                freq[a[tail]]--;
                if (freq[a[tail]] == 0) {
                    currDistinct--;
                }
                tail++;
            } else {
                tail++;
                head = tail - 1;
            }
        }

        cout << ans << endl;
    }
};


signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    memset(freq, 0, sizeof(freq));
    int t = 1;
    cin >> t;
    while(t--) {
        Solution solution;
        solution.solve();
    }

    return 0;
}
Leave a Comment