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:
How to Create a Map of Arrays in C++?
Next article icon

Construct MEX array from the given array

Last Updated : 13 Jan, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] having N distinct positive elements, the task is to generate another array B[] such that, for every ith index in the array, arr[], B[i] is the minimum positive number missing from arr[] excluding arr[i].

Examples:

Input: arr[] = {2, 1, 5, 3}
Output: B[] = {2, 1, 4, 3} 
Explanation: After excluding the arr[0], the array is {1, 5, 3}, and the minimum positive number which is not present in this array is 2. Therefore, B[0] = 2. Similarly, after excluding arr[1], arr[2], arr[3], the minimum positive numbers which are not present in the array are 1, 4 and 3, respectively. Hence, B[1] = 1, B[2] = 4, B[3] = 3.

Input: arr[] = {1, 9, 2, 4}
Output: B[] = {1, 3, 2, 3}

Naive Approach: The simplest approach to solve this problem is to traverse the array arr[] and for every index i, initialize an array hash[] and for every index j ( where j ? i), update hash[arr[j]] =1. Now traverse array hash[] from index 1 and find the minimum index k for which hash[k] = 0 and update B[i] = k. Finally, print the array B[] after completing the above step.

Time Complexity: O(N2) where N is the length of the given array.
Auxiliary Space: O(N)

Efficient Approach: To optimize the above approach, the idea is to calculate MEX of the array arr[] and traverse the array arr[]. If arr[i] is less than MEX of the array arr[] then MEX excluding this element will be arr[i] itself, and if arr[i] is greater than MEX of array A[] then MEX of the array will not change after excluding this element.

Follow the steps below to solve the problem:

  1. Initialize an array, say hash[], to store whether the value i is present in the array arr[] or not. If i is present hash[i] = 1 else hash[i] = 0.
  2. Initialize a variable MexOfArr to store MEX of array arr[] and traverse array hash[] from 1 to find the minimum index j for which hash[j] = 0, which implies that the value j is not present in the array arr[] and store MexOfArr = j.
  3. Now traverse the array, arr[] and if arr[i] is less than MexOfArr, then store B[i] = arr[i] else B[i] = MexOfArr.
  4. After completing the above steps, print elements of the array B[] as the required answer.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
#define MAXN 100001
 
// Function to construct array B[] that
// stores MEX of array A[] excluding A[i]
void constructMEX(int arr[], int N)
{
    // Stores elements present in arr[]
    int hash[MAXN] = { 0 };
 
    // Mark all values 1, if present
    for (int i = 0; i < N; i++) {
 
        hash[arr[i]] = 1;
    }
 
    // Initialize variable to store MEX
    int MexOfArr;
 
    // Find MEX of arr[]
    for (int i = 1; i < MAXN; i++) {
        if (hash[i] == 0) {
            MexOfArr = i;
            break;
        }
    }
 
    // Stores MEX for all indices
    int B[N];
 
    // Traverse the given array
    for (int i = 0; i < N; i++) {
 
        // Update MEX
        if (arr[i] < MexOfArr)
            B[i] = arr[i];
 
        // MEX default
        else
            B[i] = MexOfArr;
    }
 
    // Print the array B
    for (int i = 0; i < N; i++)
        cout << B[i] << ' ';
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 2, 1, 5, 3 };
 
    // Given size
    int N = sizeof(arr)
            / sizeof(arr[0]);
 
    // Function call
    constructMEX(arr, N);
    return 0;
}
 
 

Java




// Java program for the above approach
import java.util.*;
class GFG{
     
static int MAXN = 100001;
   
// Function to construct array
// B[] that stores MEX of array
// A[] excluding A[i]
static void constructMEX(int arr[],
                         int N)
{
  // Stores elements present
  // in arr[]
  int hash[] = new int[MAXN];
  for (int i = 0; i < N; i++)
  {
    hash[i] = 0;
  }
 
  // Mark all values 1, if
  // present
  for (int i = 0; i < N; i++)
  {
    hash[arr[i]] = 1;
  }
 
  // Initialize variable to
  // store MEX
  int MexOfArr = 0 ;
 
  // Find MEX of arr[]
  for (int i = 1; i < MAXN; i++)
  {
    if (hash[i] == 0)
    {
      MexOfArr = i;
      break;
    }
  }
 
  // Stores MEX for all
  // indices
  int B[] = new int[N];
 
  // Traverse the given array
  for (int i = 0; i < N; i++)
  {
    // Update MEX
    if (arr[i] < MexOfArr)
      B[i] = arr[i];
 
    // MEX default
    else
      B[i] = MexOfArr;
  }
 
  // Print the array B
  for (int i = 0; i < N; i++)
    System.out.print(B[i] + " ");
}
 
// Driver Code
public static void main(String[] args)
{
  // Given array arr[]
  int arr[] = {2, 1, 5, 3};
 
  // Size of array
  int N = arr.length;
 
  // Function call
  constructMEX(arr, N);
}
}
 
// This code is contributed by sanjoy_62
 
 

Python3




# Python3 program for the
# above approach
 
MAXN = 100001
 
# Function to construct
# array B[] that stores
# MEX of array A[] excluding
# A[i]
def constructMEX(arr, N):
   
    # Stores elements present
    # in arr[]
    hash = [0] * MAXN
 
    # Mark all values 1,
    # if present
    for i in range(N):
        hash[arr[i]] = 1
 
    # Initialize variable to
    # store MEX
    MexOfArr = 0
 
    # Find MEX of arr[]
    for i in range(1, MAXN):
        if (hash[i] == 0):
            MexOfArr = i
            break
 
    # Stores MEX for all
    # indices
    B = [0] * N
 
    # Traverse the given array
    for i in range(N):
 
        # Update MEX
        if (arr[i] < MexOfArr):
            B[i] = arr[i]
 
        # MEX default
        else:
            B[i] = MexOfArr
 
    # Print array B
    for i in range(N):
        print(B[i], end = " ")
 
# Driver Code
if __name__ == '__main__':
   
    # Given array
    arr = [2, 1, 5, 3]
 
    # Given size
    N = len(arr)
 
    # Function call
    constructMEX(arr, N)
 
# This code is contributed by Mohit Kumar 29
 
 

C#




// C# program for the above approach
using System;
 
class GFG{
 
static int MAXN = 100001;
   
// Function to construct array
// B[] that stores MEX of array
// A[] excluding A[i]
static void constructMEX(int[] arr,
                         int N)
{
   
  // Stores elements present
  // in arr[]
  int[] hash = new int[MAXN];
  for(int i = 0; i < N; i++)
  {
    hash[i] = 0;
  }
 
  // Mark all values 1, if
  // present
  for(int i = 0; i < N; i++)
  {
    hash[arr[i]] = 1;
  }
 
  // Initialize variable to
  // store MEX
  int MexOfArr = 0;
 
  // Find MEX of arr[]
  for(int i = 1; i < MAXN; i++)
  {
    if (hash[i] == 0)
    {
      MexOfArr = i;
      break;
    }
  }
   
  // Stores MEX for all
  // indices
  int[] B = new int[N];
 
  // Traverse the given array
  for(int i = 0; i < N; i++)
  {
     
    // Update MEX
    if (arr[i] < MexOfArr)
      B[i] = arr[i];
 
    // MEX default
    else
      B[i] = MexOfArr;
  }
 
  // Print the array B
  for(int i = 0; i < N; i++)
    Console.Write(B[i] + " ");
}
 
// Driver Code
public static void Main()
{
   
  // Given array arr[]
  int[] arr = { 2, 1, 5, 3 };
   
  // Size of array
  int N = arr.Length;
   
  // Function call
  constructMEX(arr, N);
}
}
 
// This code is contributed by code_hunt
 
 

Javascript




<script>
// Javascript program for the above approach
 
var MAXN = 100001;
 
// Function to construct array B[] that
// stores MEX of array A[] excluding A[i]
function constructMEX(arr, N)
{
    // Stores elements present in arr[]
    var hash = Array(MAXN).fill(0);
 
    // Mark all values 1, if present
    for (var i = 0; i < N; i++) {
 
        hash[arr[i]] = 1;
    }
 
    // Initialize variable to store MEX
    var MexOfArr;
 
    // Find MEX of arr[]
    for (var i = 1; i < MAXN; i++) {
        if (hash[i] == 0) {
            MexOfArr = i;
            break;
        }
    }
 
    // Stores MEX for all indices
    var B = Array(N);
 
    // Traverse the given array
    for (var i = 0; i < N; i++) {
 
        // Update MEX
        if (arr[i] < MexOfArr)
            B[i] = arr[i];
 
        // MEX default
        else
            B[i] = MexOfArr;
    }
 
    // Print the array B
    for (var i = 0; i < N; i++)
        document.write( B[i] + ' ');
}
 
// Driver Code
// Given array
var arr = [2, 1, 5, 3];
// Given size
var N = arr.length;
// Function call
constructMEX(arr, N);
 
</script>
 
 
Output: 
2 1 4 3

 

Time Complexity: O(N)
Auxiliary Space: O(N)



Next Article
How to Create a Map of Arrays in C++?
author
doreamon_
Improve
Article Tags :
  • Arrays
  • C++ Programs
  • Competitive Programming
  • DSA
  • Greedy
  • Hash
  • Mathematical
  • counting-sort
  • frequency-counting
Practice Tags :
  • Arrays
  • Greedy
  • Hash
  • Mathematical

Similar Reads

  • How to Create Array of Arrays in C++
    Arrays are basic C++ data structures that allow users to store the same data type in memory sequentially. To manage more complicated data structures, you may sometimes need to build an array of arrays, often called a 2D array or a matrix. In this article, we will learn how to create an array of arra
    3 min read
  • C++ Program to Split the array and add the first part to the end
    There is a given an array and split it from a specified position, and move the first part of array add to the end. Examples: Input : arr[] = {12, 10, 5, 6, 52, 36} k = 2 Output : arr[] = {5, 6, 52, 36, 12, 10} Explanation : Split from index 2 and first part {12, 10} add to the end . Input : arr[] =
    2 min read
  • How to Create a Map of Arrays in C++?
    In C++, the std::map is a container that stores elements in a key-value pair, whereas std::array is a sequence container that stores elements in contiguous memory. In this article, we will learn how to create a map of arrays in C++. Example: Input: arr1 = {1, 2, 3};arr2 = {4, 5, 6};arr3 = {7, 8, 9};
    2 min read
  • How to Create a Vector of Arrays in C++?
    In C++, an array is a collection of elements of a single type while vectors are dynamic arrays as they can change their size during the insertion and deletion of elements. In this article, we will learn how to create a vector of arrays in C++. Example: Input: arr1 = {1, 2, 3}; arr2 = {4, 5, 6}; arr3
    2 min read
  • How to Pass a 3D Array to a Function in C++?
    In C++, a 3D array is a multidimensional array that has three dimensions, i.e. it can grow in three directions. In this article, we will learn how to pass a 3D array to a function in C++. Pass a 3D Array to a Function in C++ Just like normal 1-dimensional arrays, we can't pass the array to a functio
    2 min read
  • How to Print an Array in C++?
    In C++, an array is a fixed-size linear data structure that stores a collection of elements of the same type in contiguous memory locations. In this article, we will learn how to print an array in C++. For Example, Input: array = {10, 20, 30, 40, 50}Output: Array Elements: 10 20 30 40 50Printing Arr
    2 min read
  • How to Copy a Vector to an Array in C++?
    In C++, vectors are dynamic arrays that can grow and reduce in size as per requirements. Sometimes, we may need to copy the contents of a vector to the POD array. In this article, we will learn how to copy a vector to an array in C++. Example: Input: myVec = {10,20,30,40,50,60};Output: array: {10,20
    2 min read
  • How to Initialize an Array in C++?
    In C++, an array is a collection of similar datatypes stored in contiguous memory locations in which each element can be accessed using their indices. In this article, we will learn how to initialize an array in C++. Initializing an Array in C++To initialize an array in C++, we can use the assignmen
    2 min read
  • How to Initialize a Dynamic Array in C++?
    In C++, dynamic arrays allow users to allocate memory dynamically. They are useful when the size of the array is not known at compile time. In this article, we will look at how to initialize a dynamic array in C++. Initializing Dynamic Arrays in C++The dynamic arrays can be initialized at the time o
    1 min read
  • How to Declare an Array in C++?
    In C++, an array is a collection of similar data types in which elements are stored in contiguous memory locations. In this article, we will learn how to declare an array in C++. Declaring an Array in C++In C++, we can declare an array by specifying the type of its elements, followed by the name of
    2 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