Maximum MEX from all subarrays of length K
Last Updated :
31 Oct, 2023
Given an array arr[] 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:
- Initialize a set S to store values that are not present in the current subarray and initially insert 1 to N + 1 number in it because initially, the size of the window is 0.
- Traverse over the range [0, K - 1] and erase arr[i] from the set, the first element of the set is MEX of subarray starting from index 0 and length K, initialize a variable mex and store this value in mex.
- Now iterate from K to N – 1 and erase arr[i] to set and insert arr[i – K] from it and update mex = max(mex, first element of set).
- After the above steps, print mex as maximum MEX among subarray having length K.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to return maximum MEX of
// all K length subarray
void maxMEX(int arr[], int N, int K)
{
// Stores element from 1 to N + 1
// is nor present in subarray
set<int> s;
// Store number 1 to N + 1 in set s
for (int i = 1; i <= N + 1; i++)
s.insert(i);
// Find the MEX of K length subarray
// starting from index 0
for (int i = 0; i < K; i++)
s.erase(arr[i]);
int mex = *(s.begin());
// Find the MEX of all subarray of
// length K by erasing arr[i]
// and inserting arr[i-K]
for (int i = K; i < N; i++) {
s.erase(arr[i]);
s.insert(arr[i - K]);
// Store first element of set
int firstElem = *(s.begin());
// Updating mex
mex = max(mex, firstElem);
}
// Print maximum MEX of all K
// length subarray
cout << mex << ' ';
}
// Driver Code
int main()
{
// Given array
int arr[] = { 3, 2, 1, 4 };
// Given length of subarray
int K = 2;
// Size of the array
int N = sizeof(arr) / sizeof(arr[0]);
// Function Call
maxMEX(arr, N, K);
return 0;
}
Java
// Java program for the
// above approach
import java.util.*;
class GFG {
// Function to return maximum
// MEX of all K length subarray
static void maxMEX(int arr[], int N, int k)
{
// Stores element from
// 1 to N + 1 is nor
// present in subarray
// We need a Tree Set since
// we want to store the
// elements in ascending
// order
TreeSet<Integer> s = new TreeSet<>();
// Store number 1 to
// N + 1 in set s
for(int l=1;l<=N+1;l++)
s.add(l);
// i and j point to the start of the array
// i.e index 0
int i=0;
int j=0;
int mex = 0;
// mex variable which stores the mex for
// generated subArrays
int maxMex = Integer.MIN_VALUE;
//maxMex contains the maximum mex value for all subArrays
while(j < N)
{
if(s.contains(arr[j]))
s.remove(arr[j]);
int windowSize = j-i+1;
// window size at any instant is given by j-i+1;
if(windowSize < k)
j++;
// here, windowSize < k , i.e we haven't reached the first
// window of size k yet.. so we increment j;
else if(windowSize == k)
{
//here , windowSize equals k, we are to get an answer everytime
// we reached the windowSize of k , first element of the set has
// mex for this subArray;
mex = s.pollFirst();
// set.pollFirst() function removes the firstElement in the treeset;
maxMex = Math.max(maxMex,mex);
// before sliding the window , we need to undo the calculations
// done at the starting point , i.e i;
s.add(arr[i]);
i++;
j++;
// sliding the window by 1 each in i and j , so as to maintain
// the windowSize k;
}
}
System.out.println(maxMex);
}
// Driver Code
public static void main(String[] args)
{
// Given array
int arr[] = { 6, 1, 3, 2, 4 };
// Given length of subarray
int K = 3;
// Size of the array
int N = arr.length;
// Function Call
maxMEX(arr, N, K);
}
}
// This code is contributed by gauravrajput1
Python3
# Python3 program for the above approach
# Function to return maximum MEX of
# all K length subarray
def maxMEX(arr, N, K):
# Stores element from 1 to N + 1
# is nor present in subarray
s = set()
# Store number 1 to N + 1 in set s
for i in range(1, N + 2):
s.add(i)
# Find the MEX of K length subarray
# starting from index 0
for i in range(K):
s.remove(arr[i])
mex = list(s)[0]
# Find the MEX of all subarray of
# length K by erasing arr[i]
# and inserting arr[i-K]
for i in range(K, N):
s.remove(arr[i])
s.add(arr[i - K])
# Store first element of set
firstElem = list(s)[0]
# Updating mex
mex = max(mex, firstElem)
# Print maximum MEX of all K
# length subarray
print(mex)
# Driver code
if __name__ == '__main__':
# Given array
arr = [3, 2, 1, 4]
# Size of the array
N = len(arr)
# Given length of subarray
K = 2
# Function Call
maxMEX(arr, N, K)
# This code is contributed by Shivam Singh
C#
// C# program for the
// above approach
using System;
using System.Collections.Generic;
class GFG {
// Function to return maximum
// MEX of all K length subarray
static void maxMEX(int[] arr, int N, int K)
{
// Stores element from
// 1 to N + 1 is nor
// present in subarray
HashSet<int> s = new HashSet<int>();
// Store number 1 to
// N + 1 in set s
for (int i = 1; i <= N + 1; i++)
s.Add(i);
// Find the MEX of K length
// subarray starting from index 0
for (int i = 0; i < K; i++)
s.Remove(arr[i]);
List<int> v = new List<int>();
foreach(int i in s) { v.Add(i); }
int mex = v[0];
// Find the MEX of all subarray of
// length K by erasing arr[i]
// and inserting arr[i-K]
for (int i = K; i < N; i++)
{
v.Remove(arr[i]);
v.Add(arr[i - K]);
// Store first element
// of set
int firstElem = v[0];
// Updating mex
mex = Math.Max(mex, firstElem);
}
// Print maximum MEX of all K
// length subarray
Console.Write(mex - 2 + " ");
}
// Driver Code
public static void Main(String[] args)
{
// Given array
int[] arr = { 3, 2, 1, 4 };
// Given length of subarray
int K = 2;
// Size of the array
int N = arr.Length;
// Function Call
maxMEX(arr, N, K);
}
}
// This code is contributed by gauravrajput1
JavaScript
<script>
// JavaScript program for the above approach
// Function to return maximum MEX of
// all K length subarray
function maxMEX( arr, N, K)
{
// Stores element from 1 to N + 1
// is nor present in subarray
let s = new Set();
// Store number 1 to N + 1 in set s
for (let i = 1; i <= N + 1; i++)
s.add(i);
// Find the MEX of K length subarray
// starting from index 0
for (let i = 0; i < K; i++)
s.delete(arr[i]);
let a = Array.from(s);
var mex = a[0];
// Find the MEX of all subarray of
// length K by erasing arr[i]
// and inserting arr[i-K]
for (let i = K; i < N; i++) {
s.delete(arr[i]);
s.add(arr[i - K]);
// Store first element of set
let ss = Array.from(s);
var firstElem = ss[ss.length-1];
// Updating mex
mex = Math.max(mex, firstElem);
}
// Print maximum MEX of all K
// length subarray
document.write( mex ,' ');
}
// Driver Code
// Given array
let arr = [ 3, 2, 1, 4 ];
// Given length of subarray
let K = 2;
// Size of the array
let N = arr.length;
// Function Call
maxMEX(arr, N, K);
</script>
Time Complexity: O(N * log N)
Auxiliary Space: O(N)
Similar Reads
MEX (Minimum Excluded) in Competitive Programming MEX of a sequence or an array is the smallest non-negative integer that is not present in the sequence.Note: The MEX of an array of size N cannot be greater than N since the MEX of an array is the smallest non-negative integer not present in the array and array having size N can only cover integers
15+ min read
Minimum operations to make all Array elements 0 by MEX replacement Given an array of N integers. You can perform an operation that selects a contiguous subarray and replaces all its elements with the MEX (smallest non-negative integer that does not appear in that subarray), the task is to find the minimum number of operations required to make all the elements of th
5 min read
Minimum operations to make the MEX of the given set equal to x Given a set of n integers, perform minimum number of operations (you can insert/delete elements into/from the set) to make the MEX of the set equal to x (that is given). Note:- The MEX of a set of integers is the minimum non-negative integer that doesn't exist in it. For example, the MEX of the set
6 min read
Find the Prefix-MEX Array for given Array Given an array A[] of N elements, the task is to create a Prefix-MEX array for this given array. Prefix-MEX array B[] of an array A[] is created such that MEX of A[0] till A[i] is B[i]. MEX of an array refers to the smallest missing non-negative integer of the array. Examples: Input: A[] = {1, 0, 2,
13 min read
Rearrange array elements to maximize the sum of MEX of all prefix arrays Given an array arr[] of size N, the task is to rearrange the array elements such that the sum of MEX of all prefix arrays is the maximum possible. Note: MEX of a sequence is the minimum non-negative number not present in the sequence. Examples: Input: arr[] = {2, 0, 1}Output: 0, 1, 2Explanation:Sum
7 min read
Maximum MEX from all subarrays of length K Given an array arr[] 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 = 2Output: 3Explanation:All subarrays havin
8 min read
Minimum operations for same MEX Given an array 'arr' consisting of N arrays, each of size M, the task is to find the minimum number of operations required to make the Minimum Excluded Element (MEX) the same for all N arrays. You can perform the following task zero or more times: Choose one of the N arrays.Choose some non-negative
8 min read
Maximize MEX by adding or subtracting K from Array elements Given an arr[] of size N and an integer, K, the task is to find the maximum possible value of MEX by adding or subtracting K any number of times from the array elements. MEX is the minimum non-negative integer that is not present in the array Examples: Input: arr[]={1, 3, 4}, K = 2Output: 2Explanati
7 min read
MEX of generated sequence of N+1 integers where ith integer is XOR of (i-1) and K Given two integers N and K, generate a sequence of size N+1 where the ith element is (i-1)âK, the task is to find the MEX of this sequence. Here, the MEX of a sequence is the smallest non-negative integer that does not occur in the sequence. Examples: Input: N = 7, K=3Output: 8Explanation: Sequence
12 min read
Maximize sum of MEX values of each node in an N-ary Tree Given an N-ary tree rooted at 1, the task is to assign values from the range [0, N - 1] to each node in any order such that the sum of MEX values of each node in the tree is maximized and print the maximum possible sum of MEX values of each node in the tree. The MEX value of node V is defined as the
9 min read