Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Rearrange array elements to maximize the sum of MEX of all prefix arrays
Next article icon

Find the Prefix-MEX Array for given Array

Last Updated : 01 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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[]: 
      • Run a for loop to find the MEX of index 0 till i.
      • Then store this MEX at index i in the resultant array B[i].
  • 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 <bits/stdc++.h>
using namespace std;
 
// Function to find 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 find 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<Integer> 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 find 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 find 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




<script>
        // JavaScript code to implement the approach
 
        // Function to find the prefix MEX
        // for each array element
        const Prefix_Mex = (A, n) => {
            // Maximum element in vector A
            let mx_element = Math.max(...A);
 
            // Store all number from 0
            // to maximum element + 1 in a set
            let s = new Set();
 
            for (let i = 0; i <= mx_element + 1; i++) {
                s.add(i);
            }
 
            // Loop to calculate Mex for each index
            let B = new Array(n).fill(0);
            for (let i = 0; i < n; i++) {
 
                // Checking if A[i] is present in set
                let it = s.has(A[i]);
 
                // If present then we erase that element
                if (it) s.delete(A[i]);
 
 
                // Store the first element of set
                // in vector B as Mex of prefix vector
                B[i] = s.values().next().value;
            }
 
            // Return the vector B
            return B;
        }
 
        // Driver code
 
        let A = [1, 0, 2, 4, 3];
        let N = A.length;
 
        // Function call
        let B = Prefix_Mex(A, N);
 
        // Print the prefix MEX array
        for (let i = 0; i < N; i++) {
            document.write(`${B[i]} `);
        }
 
        // This code is contributed by rakeshsahni
 
    </script>
 
 
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)

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;
 
// Function to compute Prefix Mex
vector<int> Prefix_Mex(vector<int>& A, int n) {
    // Create a boolean vector to track the presence of numbers
    vector<bool> b(n+1);
     
    // Initialize mex (minimum excluded value) to 0
    int mex = 0;
     
    // Result vector to store the Prefix Mex values
    vector<int> result(n);
 
    // Loop through the input vector A
    for (int i = 0; i < n; i++) {
        // Mark the current element as present
        b[A[i]] = true;
 
        // Update mex until a non-present value is found
        while (b[mex] == true) {
            mex++;
        }
 
        // Store the current mex value in the result vector
        result[i] = mex;
    }
 
    // Return the result vector
    return result;
}
 
int main()
{
    // Input vector
    vector<int> A = { 2, 1, 0, 3, 5, 4 };
 
    // Get the size of the input vector
    int n = A.size();
 
    // Compute the Prefix Mex values using the defined function
    vector<int> result = Prefix_Mex(A, n);
 
    // Print the Prefix Mex values
    for (int i = 0; i < n; i++) {
        cout << result[i] << " ";
    }
 
    // Return 0 to indicate successful execution
    return 0;
}
 
 

Java




import java.util.Arrays;
 
public class Main {
    // Function to compute Prefix Mex
    static int[] prefixMex(int[] A, int n) {
        // Create a boolean array to track the presence of numbers
        boolean[] b = new boolean[n+1];
 
        // Initialize mex (minimum excluded value) to 0
        int mex = 0;
 
        // Result array to store the Prefix Mex values
        int[] result = new int[n];
 
        // Loop through the input array A
        for (int i = 0; i < n; i++) {
            // Mark the current element as present
            b[A[i]] = true;
 
            // Update mex until a non-present value is found
            while (b[mex]) {
                mex++;
            }
 
            // Store the current mex value in the result array
            result[i] = mex;
        }
 
        // Return the result array
        return result;
    }
 
    public static void main(String[] args) {
        // Input array
        int[] A = {2, 1, 0, 3, 5, 4};
 
        // Get the size of the input array
        int n = A.length;
 
        // Compute the Prefix Mex values using the defined function
        int[] result = prefixMex(A, n);
 
        // Print the Prefix Mex values
        for (int i = 0; i < n; i++) {
            System.out.print(result[i] + " ");
        }
    }
}
 
 

Python3




def prefix_mex(A, n):
    # Create a boolean list to track the presence of numbers
    b = [False] * (n+1)
 
    # Initialize mex (minimum excluded value) to 0
    mex = 0
 
    # Result list to store the Prefix Mex values
    result = [0] * n
 
    # Loop through the input list A
    for i in range(n):
        # Mark the current element as present
        b[A[i]] = True
 
        # Update mex until a non-present value is found
        while b[mex]:
            mex += 1
 
        # Store the current mex value in the result list
        result[i] = mex
 
    # Return the result list
    return result
 
# Main
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
{
    // Function to compute Prefix Mex
    static int[] PrefixMex(int[] A, int n)
    {
        // Create a boolean array to track the presence of numbers
        bool[] b = new bool[n+1];
 
        // Initialize mex (minimum excluded value) to 0
        int mex = 0;
 
        // Result array to store the Prefix Mex values
        int[] result = new int[n];
 
        // Loop through the input array A
        for (int i = 0; i < n; i++)
        {
            // Mark the current element as present
            b[A[i]] = true;
 
            // Update mex until a non-present value is found
            while (b[mex])
            {
                mex++;
            }
 
            // Store the current mex value in the result array
            result[i] = mex;
        }
 
        // Return the result array
        return result;
    }
 
    static void Main()
    {
        // Input array
        int[] A = {2, 1, 0, 3, 5, 4};
 
        // Get the size of the input array
        int n = A.Length;
 
        // Compute the Prefix Mex values using the defined function
        int[] result = PrefixMex(A, n);
 
        // Print the Prefix Mex values
        foreach (int i in result)
        {
            Console.Write(i + " ");
        }
    }
}
 
 

Javascript




// Function to compute Prefix Mex
function prefixMex(A, n) {
    // Create a boolean array to track the presence of numbers
    let b = Array(n+1).fill(false);
 
    // Initialize mex (minimum excluded value) to 0
    let mex = 0;
 
    // Result array to store the Prefix Mex values
    let result = Array(n).fill(0);
 
    // Loop through the input array A
    for (let i = 0; i < n; i++) {
        // Mark the current element as present
        b[A[i]] = true;
 
        // Update mex until a non-present value is found
        while (b[mex]) {
            mex++;
        }
 
        // Store the current mex value in the result array
        result[i] = mex;
    }
 
    // Return the result array
    return result;
}
 
// Main
let A = [2, 1, 0, 3, 5, 4];
let n = A.length;
 
let result = prefixMex(A, n);
 
// Print the Prefix Mex values
console.log(result.join(' '));
 
 
Output
0 0 3 4 4 6               

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)



Next Article
Rearrange array elements to maximize the sum of MEX of all prefix arrays
author
piyushgupta106970
Improve
Article Tags :
  • Arrays
  • DSA
  • Greedy
  • Hash
  • cpp-set
  • prefix
Practice Tags :
  • Arrays
  • Greedy
  • Hash

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences