# Find the Prefix-MEX Array for given Array

• Difficulty Level : Medium
• Last Updated : 05 Sep, 2022

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:
• 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++

 `// C++ code to implement the approach`   `#include ` `using` `namespace` `std;`   `// Function to fint the prefix MEX` `// for each array element` `vector<``int``> Prefix_Mex(vector<``int``>& A, ``int` `n)` `{` `    ``// Maximum element in vector A` `    ``int` `mx_element = *max_element(A.begin(), A.end());`   `    ``// Store all number from 0` `    ``// to maximum element + 1 in a set` `    ``set<``int``> s;` `    ``for` `(``int` `i = 0; i <= mx_element + 1; i++) {` `        ``s.insert(i);` `    ``}`   `    ``// Loop to calculate Mex for each index` `    ``vector<``int``> B(n);` `    ``for` `(``int` `i = 0; i < n; i++) {`   `        ``// Checking if A[i] is present in set` `        ``auto` `it = s.find(A[i]);`   `        ``// If present then we erase that element` `        ``if` `(it != s.end())` `            ``s.erase(it);`   `        ``// Store the first element of set` `        ``// in vector B as Mex of prefix vector` `        ``B[i] = *s.begin();` `    ``}`   `    ``// Return the vector B` `    ``return` `B;` `}`   `// Driver code` `int` `main()` `{`   `    ``vector<``int``> A = { 1, 0, 2, 4, 3 };` `    ``int` `N = A.size();`   `    ``// Function call` `    ``vector<``int``> B = Prefix_Mex(A, N);`   `    ``// Print the prefix MEX array` `    ``for` `(``int` `i = 0; i < N; i++) {` `        ``cout << B[i] << ``" "``;` `    ``}` `    ``return` `0;` `}`

## Java

 `// Java code to implement the approach` `import` `java.util.Arrays;` `import` `java.util.LinkedHashSet;` `import` `java.util.stream.Collectors;`   `class` `GFG{`   `// Function to fint the prefix MEX` `// for each array element` `static` `int``[] Prefix_Mex(``int``[] A, ``int` `n)` `{` `  `  `    ``// Maximum element in vector A` `    ``int` `mx_element = Arrays.stream(A).max().getAsInt();`   `    ``// Store all number from 0` `    ``// to maximum element + 1 in a set` `    ``LinkedHashSet s = ``new` `LinkedHashSet<>();` `    ``for` `(``int` `i = ``0``; i <= mx_element + ``1``; i++) {` `        ``s.add(i);` `    ``}`   `    ``// Loop to calculate Mex for each index` `    ``int` `[]B = ``new` `int``[n];` `    ``for` `(``int` `i = ``0``; i < n; i++) {`   `        ``// Checking if A[i] is present in set` `        ``// If present then we erase that element` `        ``if` `(s.contains(A[i]))` `            ``s.remove(A[i]);`   `        ``// Store the first element of set` `        ``// in vector B as Mex of prefix vector` `        ``B[i] = s.stream().collect(Collectors.toList()).get(``0``);` `    ``}`   `    ``// Return the vector B` `    ``return` `B;` `}`   `// Driver code` `public` `static` `void` `main(String[] args)` `{`   `    ``int``[] A = { ``1``, ``0``, ``2``, ``4``, ``3` `};` `    ``int` `N = A.length;`   `    ``// Function call` `    ``int``[] B = Prefix_Mex(A, N);`   `    ``// Print the prefix MEX array` `    ``for` `(``int` `i = ``0``; i < N; i++) {` `        ``System.out.print(B[i]+ ``" "``);` `    ``}` `}` `}`   `// This code is contributed by shikhasingrajput`

## Python3

 `# Python code to implement the approach`   `# Function to fint the prefix MEX` `# for each array element` `def` `Prefix_Mex(A, n):` `    ``# Maximum element in vector A` `    ``mx_element ``=` `max``(A)` `    ``# Store all number from 0` `    ``# to maximum element + 1 in a set` `    ``s ``=` `{}` `    ``for` `i ``in` `range``(mx_element``+``2``):` `        ``s[i] ``=` `True`   `    ``# Loop to calculate Mex for each index` `    ``B ``=` `[``0``]``*``n` `    ``for` `i ``in` `range``(n):` `        ``# Checking if A[i] is present in set` `        ``# If present then we erase that element` `        ``if` `A[i] ``in` `s.keys():` `            ``del` `s[A[i]]` `        ``# Store the first element of set` `        ``# in vector B as Mex of prefix vector` `        ``B[i] ``=` `int``(``list``(s.keys())[``0``])` `        ``# Return the list B` `    ``return` `B`     `# Driver code` `if` `__name__ ``=``=` `"__main__"``:` `    ``A ``=` `[``1``, ``0``, ``2``, ``4``, ``3``]` `    ``N ``=` `len``(A)`   `    ``# Function call` `    ``B ``=` `Prefix_Mex(A, N)`   `    ``# Print the prefix MEX array` `    ``for` `i ``in` `range``(N):` `        ``print``(B[i], end``=``" "``)`   `# This code is contributed by Rohit Pradhan`

## C#

 `// C# code to implement the approach` `using` `System;` `using` `System.Collections.Generic;` `using` `System.Linq;` `public` `class` `GFG{`   `// Function to fint the prefix MEX` `// for each array element` `static` `int``[] Prefix_Mex(``int``[] A, ``int` `n)` `{` `  `  `    ``// Maximum element in vector A` `    ``int` `mx_element =A.Max();`   `    ``// Store all number from 0` `    ``// to maximum element + 1 in a set` `    ``HashSet<``int``> s = ``new` `HashSet<``int``>();` `    ``for` `(``int` `i = 0; i <= mx_element + 1; i++) {` `        ``s.Add(i);` `    ``}`   `    ``// Loop to calculate Mex for each index` `    ``int` `[]B = ``new` `int``[n];` `    ``for` `(``int` `i = 0; i < n; i++) {`   `        ``// Checking if A[i] is present in set` `        ``// If present then we erase that element` `        ``if` `(s.Contains(A[i]))` `            ``s.Remove(A[i]);`   `        ``// Store the first element of set` `        ``// in vector B as Mex of prefix vector` `        ``B[i] = s.FirstOrDefault();` `    ``}`   `    ``// Return the vector B` `    ``return` `B;` `}`   `// Driver code` `public` `static` `void` `Main(String[] args)` `{`   `    ``int``[] A = { 1, 0, 2, 4, 3 };` `    ``int` `N = A.Length;`   `    ``// Function call` `    ``int``[] B = Prefix_Mex(A, N);`   `    ``// Print the prefix MEX array` `    ``for` `(``int` `i = 0; i < N; i++) {` `        ``Console.Write(B[i]+ ``" "``);` `    ``}` `}` `}`   `// This code is contributed by shikhasingrajput`

## Javascript

 ``

Output

`0 2 3 3 5 `

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)

My Personal Notes arrow_drop_up
Related Articles