Find the Prefix-MEX Array for given Array
Last Updated :
01 Dec, 2023
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, 4, 3}
Output: 0 2 3 3 5
Explanation: In the array A, elements
Till 1st index, elements are [1] and mex till 1st index is 0.
Till 2nd index, elements are [1, 0] and mex till 2nd index is 2.
Till 3rd index, elements are [ 1, 0, 2] and mex till 3rd index is 3.
Till 4th index, elements are [ 1, 0, 2, 4] and mex till 4th index is 3.
Till 5th index, elements are [ 1, 0, 2, 4, 3] and mex till 5th index is 5.
So our final array B would be [0, 2, 3, 3, 5].
Input: A[] = [ 1, 2, 0 ]
Output: [ 0, 0, 3 ]
Explanation: In the array A, elements
Till 1st index, elements are [1] and mex till 1st index is 0.
Till 2nd index, elements are [1, 2] and mex till 2nd index is 0.
Till 3rd index, elements are [ 1, 2, 0] and mex till 3rd index is 3.
So our final array B would be [0, 0, 3].
Naive Approach: The simplest way to solve the problem is:
For each element at ith (0 ≤ i < N)index of the array A[], find MEX from 0 to i and store it at B[i].
Follow the steps mentioned below to implement the idea:
- Iterate over the array from i = 0 to N-1:
- For every ith index in array A[]:
- Return the resultant array B[] at the end.
Time Complexity: O(N2)
Auxiliary Space: O(N)
Efficient Approach: This approach is based on the usage of Set data structure.
A set stores data in sorted order. We can take advantage of that and store all the non-negative integers till the maximum value of the array. Then traverse through each array element and remove the visited data from set. The smallest remaining element will be the MEX for that index.
Follow the steps below to implement the idea:
- Find the maximum element of the array A[].
- Create a set and store the numbers from 0 to the maximum element in the set.
- Traverse through the array from i = 0 to N-1:
- For each element, erase that element from the set.
- Now find the smallest element remaining in the set.
- This is the prefix MEX for the ith element. Store this value in the resultant array.
- Return the resultant array as the required answer.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > Prefix_Mex(vector< int >& A, int n)
{
int mx_element = *max_element(A.begin(), A.end());
set< int > s;
for ( int i = 0; i <= mx_element + 1; i++) {
s.insert(i);
}
vector< int > B(n);
for ( int i = 0; i < n; i++) {
auto it = s.find(A[i]);
if (it != s.end())
s.erase(it);
B[i] = *s.begin();
}
return B;
}
int main()
{
vector< int > A = { 1, 0, 2, 4, 3 };
int N = A.size();
vector< int > B = Prefix_Mex(A, N);
for ( int i = 0; i < N; i++) {
cout << B[i] << " " ;
}
return 0;
}
|
Java
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.stream.Collectors;
class GFG{
static int [] Prefix_Mex( int [] A, int n)
{
int mx_element = Arrays.stream(A).max().getAsInt();
LinkedHashSet<Integer> s = new LinkedHashSet<>();
for ( int i = 0 ; i <= mx_element + 1 ; i++) {
s.add(i);
}
int []B = new int [n];
for ( int i = 0 ; i < n; i++) {
if (s.contains(A[i]))
s.remove(A[i]);
B[i] = s.stream().collect(Collectors.toList()).get( 0 );
}
return B;
}
public static void main(String[] args)
{
int [] A = { 1 , 0 , 2 , 4 , 3 };
int N = A.length;
int [] B = Prefix_Mex(A, N);
for ( int i = 0 ; i < N; i++) {
System.out.print(B[i]+ " " );
}
}
}
|
Python3
def Prefix_Mex(A, n):
mx_element = max (A)
s = {}
for i in range (mx_element + 2 ):
s[i] = True
B = [ 0 ] * n
for i in range (n):
if A[i] in s.keys():
del s[A[i]]
B[i] = int ( list (s.keys())[ 0 ])
return B
if __name__ = = "__main__" :
A = [ 1 , 0 , 2 , 4 , 3 ]
N = len (A)
B = Prefix_Mex(A, N)
for i in range (N):
print (B[i], end = " " )
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class GFG{
static int [] Prefix_Mex( int [] A, int n)
{
int mx_element =A.Max();
HashSet< int > s = new HashSet< int >();
for ( int i = 0; i <= mx_element + 1; i++) {
s.Add(i);
}
int []B = new int [n];
for ( int i = 0; i < n; i++) {
if (s.Contains(A[i]))
s.Remove(A[i]);
B[i] = s.FirstOrDefault();
}
return B;
}
public static void Main(String[] args)
{
int [] A = { 1, 0, 2, 4, 3 };
int N = A.Length;
int [] B = Prefix_Mex(A, N);
for ( int i = 0; i < N; i++) {
Console.Write(B[i]+ " " );
}
}
}
|
Javascript
<script>
const Prefix_Mex = (A, n) => {
let mx_element = Math.max(...A);
let s = new Set();
for (let i = 0; i <= mx_element + 1; i++) {
s.add(i);
}
let B = new Array(n).fill(0);
for (let i = 0; i < n; i++) {
let it = s.has(A[i]);
if (it) s. delete (A[i]);
B[i] = s.values().next().value;
}
return B;
}
let A = [1, 0, 2, 4, 3];
let N = A.length;
let B = Prefix_Mex(A, N);
for (let i = 0; i < N; i++) {
document.write(`${B[i]} `);
}
</script>
|
Time Complexity: O(N * log N )
- O(N) for iterating the vector, and
- O(log N) for inserting and deleting the element from the set.
Auxiliary Space: O(N)
Efficient Approach 2: This approach is based on using an array and a pointer to keep track of the MEX.
Follow these steps mentioned below to implement this idea:
- Find the maximum element of the array A[].
- Create a boolean array of size equal to the maximum element + 1, B[] with all values initialised as 0.
- Create a variable to track the current MEX.
- Traverse through the A[] from i = 0 to N-1:
- For each element, set the value in B[] at index equal to the value of the element at i in A[] to true.
- Update the current MEX by increasing the variable until value in B[] at MEX is true.
- Store this value in the resultant array.
- Return the resultant array as the required answer.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > Prefix_Mex(vector< int >& A, int n) {
vector< bool > b(n+1);
int mex = 0;
vector< int > result(n);
for ( int i = 0; i < n; i++) {
b[A[i]] = true ;
while (b[mex] == true ) {
mex++;
}
result[i] = mex;
}
return result;
}
int main()
{
vector< int > A = { 2, 1, 0, 3, 5, 4 };
int n = A.size();
vector< int > result = Prefix_Mex(A, n);
for ( int i = 0; i < n; i++) {
cout << result[i] << " " ;
}
return 0;
}
|
Java
import java.util.Arrays;
public class Main {
static int [] prefixMex( int [] A, int n) {
boolean [] b = new boolean [n+ 1 ];
int mex = 0 ;
int [] result = new int [n];
for ( int i = 0 ; i < n; i++) {
b[A[i]] = true ;
while (b[mex]) {
mex++;
}
result[i] = mex;
}
return result;
}
public static void main(String[] args) {
int [] A = { 2 , 1 , 0 , 3 , 5 , 4 };
int n = A.length;
int [] result = prefixMex(A, n);
for ( int i = 0 ; i < n; i++) {
System.out.print(result[i] + " " );
}
}
}
|
Python3
def prefix_mex(A, n):
b = [ False ] * (n + 1 )
mex = 0
result = [ 0 ] * n
for i in range (n):
b[A[i]] = True
while b[mex]:
mex + = 1
result[i] = mex
return result
A = [ 2 , 1 , 0 , 3 , 5 , 4 ]
n = len (A)
result = prefix_mex(A, n)
for i in result:
print (i, end = ' ' )
|
C#
using System;
class Program
{
static int [] PrefixMex( int [] A, int n)
{
bool [] b = new bool [n+1];
int mex = 0;
int [] result = new int [n];
for ( int i = 0; i < n; i++)
{
b[A[i]] = true ;
while (b[mex])
{
mex++;
}
result[i] = mex;
}
return result;
}
static void Main()
{
int [] A = {2, 1, 0, 3, 5, 4};
int n = A.Length;
int [] result = PrefixMex(A, n);
foreach ( int i in result)
{
Console.Write(i + " " );
}
}
}
|
Javascript
function prefixMex(A, n) {
let b = Array(n+1).fill( false );
let mex = 0;
let result = Array(n).fill(0);
for (let i = 0; i < n; i++) {
b[A[i]] = true ;
while (b[mex]) {
mex++;
}
result[i] = mex;
}
return result;
}
let A = [2, 1, 0, 3, 5, 4];
let n = A.length;
let result = prefixMex(A, n);
console.log(result.join( ' ' ));
|
Time Complexity: O(N)
- O(N) for iterating the vector.
- O(N) for updating the MEX. Important thing to note is that the inner while loop can run only N times independent of the outer for loop.
Space Complexity: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...