Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code : MEX Game 1

#include <bits/stdc++.h>
using namespace std;

#define endl "\n"

void solve(vector<int> &a) {
    int n = a.size();

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

    // Answer : 1st missing element or second smallest element with frequency 1
    bool once = false;
    int ans = -1;
    for (int i = 0; i < n + 5; i++) {
        if (freq[i] == 0) {
            ans = i;
            break;
        }
        if (freq[i] == 1) {
            if (once) {
                ans = i;
                break;
            }
            once = true;
        }
    }

    cout << ans << endl;
}

int main() {
    int t;
    cin >> t;
    for (int zz = 0; zz < t; zz++) {
        int n;
        cin >> n;
        vector<int> a(n);
        for (int i = 0; i < n; i++) {
            cin >> a[i];
        }
        solve(a);
    }
    return 0;
}