Minimum MEX from all subarrays of length K | C ++ program for the above approach ; Function to return minimum MEX from all K - length subarrays ; Stores element from [ 1 , N + 1 ] which are not present in subarray ; Store number 1 to N + 1 in set s ; Find the MEX of K - length subarray starting from index 0 ; Find the MEX of all subarrays of length K by erasing arr [ i ] and inserting arr [ i - K ] ; Store first element of set ; Updating the mex ; Print minimum MEX of all K length subarray ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumMEX ( int arr [ ] , int N , int K ) { set < int > s ; for ( int i = 1 ; i <= N + 1 ; i ++ ) s . insert ( i ) ; for ( int i = 0 ; i < K ; i ++ ) s . erase ( arr [ i ] ) ; int mex = * ( s . begin ( ) ) ; for ( int i = K ; i < N ; i ++ ) { s . erase ( arr [ i ] ) ; s . insert ( arr [ i - K ] ) ; int firstElem = * ( s . begin ( ) ) ; mex = min ( mex , firstElem ) ; } cout << mex << ' ▁ ' ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int K = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minimumMEX ( arr , N , K ) ; return 0 ; }