Minimum Mex from all subarrays of length K

Given an array arr[] consisting of N distinct positive integers and an integer K, the task is to find the minimum MEX from all subarrays of length K.

The MEX is the smallest positive integer that is not present in the array.


Input: arr[] = {1, 2, 3}, K = 2Output: 1Explanation:All subarrays of length 2 are {1, 2}, {2, 3}.In subarray {1, 2}, the smallest positive integer which is not present is 3.In subarray {2, 3}, the smallest positive integer which is not present is 1.Therefore, the minimum of all the MEX for all subarrays of length K (= 2) is 1.
Input: arr[] = {1, 2, 3, 4, 5, 6}, K = 3Output: 1

Naive Approach: The simplest approach to solve the problem is to generate all subarrays of length K and find the MEX for every subarray. After finding all the MEX, print the minimum of those obtained.Time Complexity: O(K * N2)Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized by using a Set and Sliding Window technique. Follow the steps below to solve the problem:Initialize a variable, say mex, to store the minimum among all the MEX of subarrays of size K.
Initialize a set S to store values that are not present in the current subarray. Initially insert all numbers from the range [1, N + 1] in it, because initially, the size of the window is 0.
Iterate over the range [0, K – 1] and erase the element arr[i] from the set.
Now, the first element of the set is MEX of subarray over the range [0, K] and store this value in mex.
Now, iterate over the range[K, N – 1] and perform the following steps:

After completing the above steps, print the value of mex as the minimum MEX among all the subarrays of size K.
Below is the implementation of the above approach:


using namespace std;

void minimumMEX(int arr[], int N, int K)
    set s;
    for (int i = 1; i