MEX (Minimum Excluded) in Competitive Programming
Last Updated :
14 Feb, 2025
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 from 0 to N-1. Therefore, the MEX of an array with N elements cannot be greater than N itself.
Examples
Input: S[] = {1, 2, 0, 4, 5}
Output: 3
Explanation: The given sequence contains 0, 1, 2, 4, and 5. The smallest non-negative integer missing from the sequence is 3, as all numbers before it are present.
Input: S[] = {2, 0, 3, 10}
Output: 1
Explanation: The given sequence contains 0, 2, 3, and 10. The smallest non-negative integer missing from the sequence is 1, as 0 is present but 1 is not.
Input: S[] = {1, 2, 3, 4, 5}
Output: 0
Explanation: The given sequence contains 1, 2, 3, 4, and 5, but 0 is missing. Since 0 is the smallest non-negative integer not present in the sequence, it is the MEX.
How to Find MEX of an array (Without Updates) ?
The idea is to use a map to store frequency of each element of an array. Then, iterate through non-negative integers from 0 to N, and return the first integer with a frequency of 0 in the map. This integer represents the smallest non-negative integer not present in the array, which is the MEX.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the MEX of the array
int mex(vector<int>& arr, int N)
{
// Create a map to store the frequency of each element
map<int, int> mp;
for (int i = 0; i < N; i++) {
mp[arr[i]]++;
}
// Initialize MEX to 0
int mex = 0;
// Iterate through non-negative integers from 0 to N
for (int i = 0; i <= N; i++) {
// Find the first integer with a frequency of 0 in the map
if (mp[i] == 0) {
mex = i;
break;
}
}
// Return MEX as the answer
return mex;
}
int main()
{
// Example array
vector<int> arr = { 1, 0, 2, 4 };
int N = arr.size();
// Call the mex function and print the result
cout << "MEX of the array: " << mex(arr, N) << endl;
return 0;
}
Java
import java.util.HashMap;
public class MinimumExcludedValue {
// Function to find the MEX of the array
static int mex(int[] arr, int N) {
// Create a map to store the frequency of each element
HashMap<Integer, Integer> mp = new HashMap<>();
for (int i = 0; i < N; i++) {
mp.put(arr[i], mp.getOrDefault(arr[i], 0) + 1);
}
// Initialize MEX to 0
int mex = 0;
// Iterate through non-negative integers from 0 to N
for (int i = 0; i <= N; i++) {
// Find the first integer with a frequency of 0 in the map
if (!mp.containsKey(i)) {
mex = i;
break;
}
}
// Return MEX as the answer
return mex;
}
public static void main(String[] args) {
// Example array
int[] arr = {1, 0, 2, 4};
int N = arr.length;
// Call the mex function and print the result
System.out.println("MEX of the array: " + mex(arr, N));
}
}
Python
# Function to find the MEX of the array
def mex(arr):
# Create a dictionary to store the frequency of each element
freq_map = {}
for num in arr:
freq_map[num] = freq_map.get(num, 0) + 1
# Initialize MEX to 0
mex_val = 0
# Iterate through non-negative integers from 0 to N
N = len(arr)
for i in range(N + 1):
# Find the first integer with a frequency of 0 in the dictionary
if i not in freq_map:
mex_val = i
break
# Return MEX as the answer
return mex_val
# Main function
if __name__ == "__main__":
# Example array
arr = [1, 0, 2, 4]
# Call the mex function and print the result
print("MEX of the array:", mex(arr))
C#
using System;
using System.Collections.Generic;
using System.Linq;
class MexAlgorithm
{
static int Mex(int[] arr, int N)
{
Dictionary<int, int> freqMap = new Dictionary<int, int>();
// Store the frequency of each element in the array
for (int i = 0; i < N; i++)
{
if (freqMap.ContainsKey(arr[i]))
{
freqMap[arr[i]]++;
}
else
{
freqMap[arr[i]] = 1;
}
}
int mex = 0;
// Iterate through non-negative integers from 0 to N
for (int i = 0; i <= N; i++)
{
// Find the first integer with a frequency of 0 in the dictionary
if (!freqMap.ContainsKey(i) || freqMap[i] == 0)
{
mex = i;
break;
}
}
return mex;
}
static void Main()
{
// Example array
int[] arr = { 1, 0, 2, 4 };
int N = arr.Length;
// Call the Mex function and print the result
Console.WriteLine("MEX of the array: " + Mex(arr, N));
}
}
JavaScript
// Function to find the MEX of the array
function mex(arr, N) {
// Create a map to store the frequency of each element
const mp = new Map();
for (let i = 0; i < N; i++) {
if (mp.has(arr[i])) {
mp.set(arr[i], mp.get(arr[i]) + 1);
} else {
mp.set(arr[i], 1);
}
}
// Initialize MEX to 0
let mex = 0;
// Iterate through non-negative integers from 0 to N
for (let i = 0; i <= N; i++) {
// Find the first integer with a frequency of 0 in the map
if (!mp.has(i) || mp.get(i) === 0) {
mex = i;
break;
}
}
// Return MEX as the answer
return mex;
}
// Main function
function main() {
// Example array
const arr = [1, 0, 2, 4];
const N = arr.length;
// Call the mex function and print the result
console.log("MEX of the array:", mex(arr, N));
}
// Call the main function
main();
OutputMEX of the array: 3
Time Complexity: O(N log N) due to insertions in the map and an additional O(N) iteration for finding the MEX, making it effectively O(N log N).
Auxiliary Space : O(N) for storing the frequency map.
Further Optimization: We can use a Set instead of map to optimize the space used. However time and space complexity remain the same.
How to Find MEX of an array (With Updates) ?
Given an array arr of size N, and q queries. In each query you are given two numbers (idx, val), you have to update the element at index idx with value val. The task is to determine the MEX of the array after each query.
Approach:
The idea is to use a map to store frequency of each element of an array. Then insert all the numbers in the set from 0 to N which are not present in the array. For each query, update the array and maintain the map and set accordingly. The MEX for each query is determined by selecting the smallest element from the set and added to the result.
Step-by-step approach:
- Create a map to store the frequency of array elements and a set to store the elements(from 0 to N) which are not present in the array.
- For each query.
- Decrement the frequency of the element which is being replaced. If the frequency becomes 0, that element is added to set since it is not present in the array.
- Increment the frequency of the updated element. Remove the updated element from the set if the set contains it, since the updated element will be present in the set.
- The MEX for each query is determined by selecting the smallest element from the set and added to the result.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to calculate the MEX of an array after a series
// of queries
vector<int> mex(vector<int>& arr, int N,
vector<vector<int> > queries, int q)
{
// Initialize a map to store element frequencies
map<int, int> mp;
// Initialize a set to store non-present elements
set<int> st;
// Populate the map for the initial array
for (int i = 0; i < N; i++) {
mp[arr[i]]++;
}
// Add the elements to set which are not present in the
// array.
for (int i = 0; i <= N; i++) {
if (mp[i] == 0)
st.insert(i);
}
// Initialize a vector to store MEX values after each
// query
vector<int> mex;
// Process each query
for (int i = 0; i < q; i++) {
int idx = queries[i][0];
int val = queries[i][1];
// Update the frequency of element which being
// replaced.
mp[arr[idx]]--;
// If the frequency of element which is being
// replaced becomes 0, add it to set.
if (mp[arr[idx]] == 0) {
st.insert(arr[idx]);
}
arr[idx] = val;
mp[arr[idx]]++;
// If the updated element is in the set, remove it
if (st.find(arr[idx]) != st.end())
st.erase(arr[idx]);
// Calculate the MEX and add it to the result vector
int ans = *st.begin();
mex.push_back(ans);
}
return mex;
}
// Driver Code
int main()
{
// Example array
vector<int> arr = { 1, 0, 2, 4, 7 };
int N = arr.size();
// Example queries
vector<vector<int> > queries
= { { 1, 3 }, { 0, 0 }, { 4, 1 }, { 2, 10 } };
int q = queries.size();
// Call the 'mex' function to calculate MEX values after
// each query
vector<int> ans = mex(arr, N, queries, q);
// Print the results
for (int i = 0; i < q; i++) {
cout << "MEX of the array after query " << i + 1
<< " : " << ans[i] << endl;
}
return 0;
}
Java
import java.util.*;
public class Main {
// Function to calculate the MEX of an array after a series
// of queries
static List<Integer> mex(List<Integer> arr, int N,
List<List<Integer>> queries, int q) {
// Initialize a map to store element frequencies
Map<Integer, Integer> mp = new HashMap<>();
// Initialize a set to store non-present elements
TreeSet<Integer> st = new TreeSet<>();
// Populate the map for the initial array
for (int i = 0; i < N; i++) {
mp.put(arr.get(i), mp.getOrDefault(arr.get(i), 0) + 1);
}
// Add the elements to set which are not present in the array
for (int i = 0; i <= N; i++) {
if (!mp.containsKey(i))
st.add(i);
}
// Initialize a list to store MEX values after each query
List<Integer> mex = new ArrayList<>();
// Process each query
for (int i = 0; i < q; i++) {
int idx = queries.get(i).get(0);
int val = queries.get(i).get(1);
// Update the frequency of element which is being replaced
mp.put(arr.get(idx), mp.get(arr.get(idx)) - 1);
// If the frequency of the element which is being replaced becomes 0, add it to set
if (mp.get(arr.get(idx)) == 0) {
st.add(arr.get(idx));
}
arr.set(idx, val);
mp.put(val, mp.getOrDefault(val, 0) + 1);
// If the updated element is in the set, remove it
if (st.contains(arr.get(idx)))
st.remove(arr.get(idx));
// Calculate the MEX and add it to the result list
int ans = st.first();
mex.add(ans);
}
return mex;
}
// Driver Code
public static void main(String[] args) {
// Example array
List<Integer> arr = new ArrayList<>(Arrays.asList(1, 0, 2, 4, 7));
int N = arr.size();
// Example queries
List<List<Integer>> queries = new ArrayList<>(
Arrays.asList(
Arrays.asList(1, 3),
Arrays.asList(0, 0),
Arrays.asList(4, 1),
Arrays.asList(2, 10)
)
);
int q = queries.size();
// Call the 'mex' function to calculate MEX values after each query
List<Integer> ans = mex(arr, N, queries, q);
// Print the results
for (int i = 0; i < q; i++) {
System.out.println("MEX of the array after query " + (i + 1) + " : " + ans.get(i));
}
}
}
Python
def mex(arr, N, queries, q):
# Initialize a dictionary to store element frequencies
mp = {}
# Initialize a set to store non-present elements
st = set()
# Populate the dictionary for the initial array
for num in arr:
mp[num] = mp.get(num, 0) + 1
# Add the elements to set which are not present in the array.
for i in range(N + 1):
if i not in mp:
st.add(i)
mex = [] # Initialize a list to store MEX values after each query
# Process each query
for i in range(q):
idx, val = queries[i]
# Update the frequency of the element being replaced.
mp[arr[idx]] -= 1
# If the frequency of the element being replaced becomes 0, add it to the set.
if mp[arr[idx]] == 0:
st.add(arr[idx])
arr[idx] = val
# Update the frequency of the new element.
mp[val] = mp.get(val, 0) + 1
# If the updated element is in the set, remove it.
if arr[idx] in st:
st.remove(arr[idx])
# Calculate the MEX and add it to the result list
ans = min(st)
mex.append(ans)
return mex
# Example array
arr = [1, 0, 2, 4, 7]
N = len(arr)
# Example queries
queries = [
[1, 3],
[0, 0],
[4, 1],
[2, 10]
]
q = len(queries)
# Call the 'mex' function to calculate MEX values after each query
ans = mex(arr, N, queries, q)
# Print the results
for i in range(q):
print(f"MEX of the array after query {i + 1}: {ans[i]}")
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
// Function to calculate the MEX of an array after a series
// of queries
static List<int> Mex(List<int> arr, int N, List<List<int>> queries, int q)
{
// Initialize a dictionary to store element frequencies
Dictionary<int, int> mp = new Dictionary<int, int>();
// Initialize a HashSet to store non-present elements
HashSet<int> st = new HashSet<int>();
// Populate the dictionary for the initial array
foreach (int num in arr)
{
if (mp.ContainsKey(num))
mp[num]++;
else
mp[num] = 1;
}
// Add the elements to set which are not present in the array.
for (int i = 0; i <= N; i++)
{
if (!mp.ContainsKey(i))
st.Add(i);
}
// Initialize a list to store MEX values after each query
List<int> mex = new List<int>();
// Process each query
foreach (List<int> query in queries)
{
int idx = query[0];
int val = query[1];
// Update the frequency of element which is being replaced.
mp[arr[idx]]--;
// If the frequency of element which is being replaced becomes 0, add it to set.
if (mp[arr[idx]] == 0)
st.Add(arr[idx]);
arr[idx] = val;
if (mp.ContainsKey(val))
mp[val]++;
else
mp[val] = 1;
// If the updated element is in the set, remove it
if (st.Contains(val))
st.Remove(val);
// Calculate the MEX and add it to the result list
int ans = st.Min();
mex.Add(ans);
}
return mex;
}
// Driver Code
static void Main(string[] args)
{
// Example array
List<int> arr = new List<int> { 1, 0, 2, 4, 7 };
int N = arr.Count;
// Example queries
List<List<int>> queries = new List<List<int>>
{
new List<int> { 1, 3 },
new List<int> { 0, 0 },
new List<int> { 4, 1 },
new List<int> { 2, 10 }
};
int q = queries.Count;
// Call the 'Mex' function to calculate MEX values after each query
List<int> ans = Mex(arr, N, queries, q);
// Print the results
for (int i = 0; i < q; i++)
{
Console.WriteLine($"MEX of the array after query {i + 1} : {ans[i]}");
}
}
}
JavaScript
function calculateMex(arr, N, queries, q) {
// Initialize a dictionary to store element frequencies
let mp = new Map();
// Initialize a Set to store non-present elements
let st = new Set();
// Populate the dictionary for the initial array
arr.forEach((num) => {
mp.set(num, (mp.get(num) || 0) + 1);
});
// Add the elements to set which are not present in the array
for (let i = 0; i <= N; i++) {
if (!mp.has(i)) {
st.add(i);
}
}
// Initialize a list to store MEX values after each query
let mex = [];
// Process each query
for (let i = 0; i < q; i++) {
let idx = queries[i][0];
let val = queries[i][1];
// Update the frequency of element which is being replaced
mp.set(arr[idx], mp.get(arr[idx]) - 1);
// If the frequency of element which is being replaced becomes 0, add it to set
if (mp.get(arr[idx]) === 0) {
st.add(arr[idx]);
}
arr[idx] = val;
if (mp.has(val)) {
mp.set(val, mp.get(val) + 1);
} else {
mp.set(val, 1);
}
// If the updated element is in the set, remove it
if (st.has(val)) {
st.delete(val);
}
// Calculate the MEX and add it to the result list
let ans = Math.min(...Array.from(st));
mex.push(ans);
}
return mex;
}
// Example array
let arr = [1, 0, 2, 4, 7];
let N = arr.length;
// Example queries
let queries = [
[1, 3],
[0, 0],
[4, 1],
[2, 10]
];
let q = queries.length;
// Call the 'calculateMex' function to calculate MEX values after each query
let ans = calculateMex(arr, N, queries, q);
// Print the results
for (let i = 0; i < q; i++) {
console.log(`MEX of the array after query ${i + 1} : ${ans[i]}`);
}
OutputMEX of the array after query 1 : 0
MEX of the array after query 2 : 1
MEX of the array after query 3 : 5
MEX of the array after query 4 : 2
Time Complexity: O(N + Q log N), O(N) for initialization, O(log N) for each query due to set operations.
Auxiliary Space: O(N), for the frequency map and set.
How to solve MEX related problems in Competitive Programming ?
MEX Related tasks usually involves finding MEX of the array while updating its elements. Some of the common characteristics of MEX related tasks include:
- Array Updates - In general we are generally given queries in which we have either add, remove or update the values of array and the task involves finding the MEX after each such query.
- Data Structures- To optimally compute MEX after each query, set and maps are generally used because both provide fast lookup time for the elements (log n), also they keep elements sorted making it easier to find the minimum non-present element (MEX).
Let us consider few problems involving MEX:
Problem 1: Given an empty array arr[] and a integer m. You are given q queries. In ith query you add a element yi to the array. After each query you can perform the following operation any number of times: Choose an element arrj and set arrj to arrj +m or arrj -m. The task is maximize the value of MEX of array arr after each query.
The problem can be solved in following way:
Observation: We need to firstly observe that after applying the operation: arrj +m or arrj -m on an element arrj, its modulo with m still remains the same after the operation.
Keep the track of Frequency: We keep track of frequency of remainders when divided by m, i.e., for each number [0,m-1] keep track of its frequency with each query. Let freq0 , freq1 ,......, freqm-1 be the frequency of remainders 0, 1, ..... m-1.
Query Updates: During each query, we update the frequency of the remainder, by keeping the set sorted based on frequency and remainder. For example, if the query adds an element y
, we calculate y % m
to determine its remainder when divided by m
and then update its frequency.
MEX Calculation: In each query after updating the frequency of remainder we will find the minimum of {freq0 , freq1 ,......, freqm-1 }. If frqj is remainder with minimum frequency the maximum MEX will be equal to: j*frqj + j.
For example:- Suppose m=5 and frequency of remainders 0, 1, 2, 3, 4 are 3, 4, 4, 2 ,5 respectively. The minimum frequency is of remainder 3 with frequency 2. Since frequency of remainder 3 is 2, elements 3 and 8 will be present in the array by performing the operations. So the MEX will be 13 (2*10+3) in this case.
Problem 2: Given an array of n integers each integer lies in range [0,N]. The task is to make the array exactly {0, 1, 2,... , N-1} in almost 2*n operations. In one operation you can pick any element of the array and replace it with MEX of the array.
The problem can be solved in following way:
Observation: MEX of the array after each operation will lie between [0,N] and in the final array for each index i, arri = i. Let cnt be the number of indexes such that arri is not equal to i. Thus the cnt represents number of indexes for which we have to change the value of that index to its correct value.
Perform the Operations: In each operation we will firstly find the MEX of the array. Now we have 2 cases:
Case 1: When Mex of the array is between [0,N-1]: In this case we will simply put the MEX of the array in its correct index, i.e., if min_exc represents the MEX of the array then we will put min_exc in the index min_exc, this will decrease the value of cnt by 1.
Case 2: When Mex of the array is N: In this case, we will put the MEX of the array in any of the index for which arri is not equal to i. The value of cnt will remain the same.
Correctness: The above approach will convert array arr to {0,1,2, .... , N-1} in almost 2*N operations. The maximum value of cnt can be N, and the above approach decreases the value of cnt will by 1 in almost 2 operations because each time we encounter Case 2(MEX of the array is N), next time we perform the operation, we will get Case 1(MEX of the array is not N) since N was inserted in the array in last operation so MEX will not be N. Thus, we will Case 1 in which value of cnt will be decreased by 1. Hence, it takes almost 2*N operations to make the value of cnt 0.
Practice Problems on MEX:
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