Minimum MEX from all subarrays of length K | Java 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
import java . util . HashSet ; class GFG { static void minimumMEX ( int arr [ ] , int N , int K ) { HashSet < Integer > s = new HashSet < Integer > ( ) ; 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 . iterator ( ) . next ( ) ; for ( int i = K ; i < N ; i ++ ) { s . remove ( arr [ i ] ) ; s . add ( arr [ i - K ] ) ; int firstElem = s . iterator ( ) . next ( ) ; mex = Math . min ( mex , firstElem ) ; } System . out . print ( mex + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int K = 3 ; int N = arr . length ; minimumMEX ( arr , N , K ) ; } }