Find the MEX of given Array
Last Updated :
07 Sep, 2022
You are given an array arr[] of size N, the task is to determine the MEX of the array.
MEX is the smallest whole number that is not present in the array.
Examples:
Input: arr[] = {1, 0, 2, 4}
Output: 3
Explanation: 3 is the smallest whole number that is not present in the array
Input: arr[] = {-1, -5, 0, 4}
Output: 1
Explanation: 1 is the smallest whole number that is missing in the array.
Approach: Follow the below idea to solve the problem
Sort the array in increasing order and find the first number starting from 0 which is not present in the array.
Follow the steps to solve the problem:
- Sort the array.
- Initialize a variable mex = 0.
- Travel over the array from index 0 to N-1.
- If the element is equal to mex
- Increment mex by 1 i.e., mex = mex + 1
- Else continue the iteration
- Return mex as the final answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int mex(vector< int > &arr, int N)
{
sort(arr.begin(), arr.end());
int mex = 0;
for ( int idx = 0; idx < N; idx++)
{
if (arr[idx] == mex)
{
mex += 1;
}
}
return mex;
}
int main()
{
vector< int > arr = {1, 0, 2, 4};
int N = arr.size();
cout << mex(arr, N) << endl;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static int mex( int [] arr, int N)
{
Arrays.sort(arr);
int mex = 0 ;
for ( int idx = 0 ; idx < N; idx++) {
if (arr[idx] == mex) {
mex += 1 ;
}
}
return mex;
}
public static void main(String[] args)
{
int [] arr = { 1 , 0 , 2 , 4 };
int N = arr.length;
System.out.print(mex(arr, N));
}
}
|
Python3
def mex(arr, N):
arr.sort()
mex = 0
for idx in range (N):
if arr[idx] = = mex:
mex + = 1
return mex
if __name__ = = '__main__' :
arr = [ 1 , 0 , 2 , 4 ]
N = len (arr)
print (mex(arr, N))
|
C#
using System;
class GFG {
static int mex( int [] arr, int N)
{
Array.Sort(arr);
int mex = 0;
for ( int idx = 0; idx < N; idx++) {
if (arr[idx] == mex) {
mex += 1;
}
}
return mex;
}
public static void Main()
{
int [] arr = { 1, 0, 2, 4 };
int N = arr.Length;
Console.Write(mex(arr, N));
}
}
|
Javascript
<script>
function mex(arr, N){
arr.sort();
let mex = 0;
let idx = 0;
for (idx = 0; idx < N; idx++){
if (arr[idx] == mex){
mex += 1;
}
}
return mex;
}
let arr = [1, 0, 2, 4];
let N = arr.length;
document.write(mex(arr, N));
</script>
|
Time Complexity: O(N * logN)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...