Official

C - Max MEX Editorial by en_translator


For all non-negative integers \(x\), the following fact holds:
To make \(MEX\) strictly greater than \(x\), you need to choose \(x\) as an element of \(B\). Conversely, duplicating elements do not affect to \(MEX\), it is no use choosing \(x\) twice or more.

This fact leads to the following algorithm:

  • For \(i=0,1,\dots,K-1\), repeat the following:
    • If \(A\) contains \(i\), pick it. Now we know that the answer is at least \(i+1\).
    • Otherwise, we cannot make \(MEX\) greater than \(i\), so we know that the answer is \(i\). Terminate the program now.
  • If the loop above does not determine the answer, then we can make \(B\) a permutation of \((0,1,\dots,K-1)\), so the answer is \(K\).

Sample code (C++):

#include<bits/stdc++.h>

using namespace std;

int main(){
  int n,k;
  cin >> n >> k;
  set<int> st;
  for(int i=0;i<n;i++){
    int a;
    cin >> a;
    st.insert(a);
  }
  for(int i=0;i<k;i++){
    if(st.find(i)==st.end()){
      cout << i << "\n";
      return 0;
    }
  }
  cout << k << "\n";
  return 0;
}

posted:
last update: