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
using System ; using System . Collections . Generic ; using System . Linq ; class GFG { static void minimumMEX ( int [ ] arr , int N , int K ) { HashSet < int > s = new HashSet < int > ( ) ; for ( int i = 1 ; i <= N + 1 ; i ++ ) s . Add ( i ) ; for ( int i = 0 ; i < K ; i ++ ) s . Remove ( arr [ i ] ) ; int mex = s . First ( ) ; for ( int i = K ; i < N ; i ++ ) { s . Remove ( arr [ i ] ) ; s . Add ( arr [ i - K ] ) ; int firstElem = s . First ( ) ; mex = Math . Min ( mex , firstElem ) ; } Console . Write ( mex + " ▁ " ) ; } static void Main ( ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 , 6 } ; int K = 3 ; int N = arr . Length ; minimumMEX ( arr , N , K ) ; } }