![]() |
VOOZH | about |
Given an arrayarr[] consisting of N distinct integers and an integer K, the task is to find the maximum MEX from all subarrays of length K.
The MEX is the smallest positive integer that is not present in the array.
Examples:
Input: arr[] = {3, 2, 1, 4}, K = 2
Output: 3
Explanation:
All subarrays having length 2 are {3, 2}, {2, 1}, {1, 4}.
In subarray {3, 2}, the smallest positive integer which is not present is 1.
In subarray {2, 1}, the smallest positive integer which is not present is 3.
In subarray {1, 4}, the smallest positive integer which is not present is 2.Input: arr[] = {6, 1, 3, 2, 4}, K = 3
Output: 4
Explanation:
All subarrays having length 3 are {6, 1, 3}, {1, 3, 2}, {3, 2, 4}
In subarray {6, 1, 3}, the smallest positive integer which is not present is 2.
In subarray {1, 3, 2}, the smallest positive integer which is not present is 4.
In subarray {3, 2, 4}, the smallest positive integer which is not present is 1.
Naive Approach: The simplest approach is to generate all subarrays of length K and find MEX of every subarray. After finding all the MEX, print the maximum of those obtained.
Time Complexity: O(K * N2)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to use the data structure Set and Sliding Window Technique. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
3
Time Complexity: O(N * log N)
Auxiliary Space: O(N)