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 Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Maximum MEX from all subarrays of length K
Next article icon

Rearrange array elements to maximize the sum of MEX of all prefix arrays

Last Updated : 31 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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, 2
Explanation:
Sum of MEX of all prefix arrays of all possible permutations of the given array:
arr[] = {0, 1, 2}, Mex(0) + Mex(0, 1) + Mex(0, 1, 2) = 1 + 2 + 3 = 6
arr[] = {1, 0, 2}, Mex(1) + Mex(1, 0) + Mex(1, 0, 2) = 0 + 2 + 3 = 5
arr[] = {2, 0, 1}, Mex(2) + Mex(2, 0) + Mex(2, 0, 1) = 0 + 1 + 3 = 4
arr[] = {0, 2, 1}, Mex(0) + Mex(0, 2) + Mex(0, 2, 1) = 1 + 1 + 3 = 5
arr[] = {1, 2, 0}, Mex(1) + Mex(1, 2) + Mex(1, 2, 0) = 0 + 0 + 3 = 3
arr[] = {2, 1, 0}, Mex(2) + Mex(2, 1) + Mex(2, 1, 0) = 0 + 0 + 3 = 3
Hence, the maximum sum possible is 6.

Input: arr[] = {1, 0, 0}
Output: 0, 1, 0
Explanation:
Sum of MEX of all prefix arrays of all possible permutations of the given array:
arr[]={1, 0, 0}, Mex(1) + Mex(1, 0) + Mex(1, 0, 0) = 0 + 2 + 2 = 4
arr[]={0, 1, 0}, Mex(0) + Mex(0, 1) + Mex(0, 1, 0) = 1 + 2 + 2 = 5
arr[]={0, 0, 1}, Mex(0) + Mex(0, 0) + Mex(0, 0, 1) = 1 + 1 + 2 = 4
Hence, the maximum value is 5 for the arrangement, arr[]={0, 1, 0}.

 

Naive Approach: The simplest approach is to generate all possible permutations of the given array arr[] and then for each permutation, find the value of MEX of all the prefix arrays, while keeping track of the overall maximum value. After iterating over all possible permutations, print the permutation having the largest value.

Time Complexity: O(N2 * N!)
Auxiliary Space: O(N)

Efficient Approach: The optimal idea is based on the observation that the sum of MEX of prefix arrays will be maximum when all the distinct elements are arranged in increasing order and the duplicates are present at the end of the array. 
Follow the steps below to solve the problem:

  • Initialize a vector of integers, say ans, to store the required arrangement.
  • Sort the array arr[] in increasing order.
  • Traverse the array arr[] and push all distinct elements into the array ans[].
  • Again traverse the array arr[] and push all the remaining duplicate elements into the array ans[].
  • After completing the above steps, print the array ans[].

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum sum of
// MEX of prefix arrays for any
// arrangement of the given array
void maximumMex(int arr[], int N)
{
 
    // Stores the final arrangement
    vector<int> ans;
 
    // Sort the array in increasing order
    sort(arr, arr + N);
 
    // Iterate over the array arr[]
    for (int i = 0; i < N; i++) {
        if (i == 0 || arr[i] != arr[i - 1])
            ans.push_back(arr[i]);
    }
 
    // Iterate over the array, arr[]
    // and push the remaining occurrences
    // of the elements into ans[]
    for (int i = 0; i < N; i++) {
        if (i > 0 && arr[i] == arr[i - 1])
            ans.push_back(arr[i]);
    }
 
    // Print the array, ans[]
    for (int i = 0; i < N; i++)
        cout << ans[i] << " ";
}
 
// Driver Code
int main()
{
 
    // Given array
    int arr[] = { 1, 0, 0 };
 
    // Store the size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    maximumMex(arr, N);
 
    return 0;
}
 
 

Java




// Java program for the above approach
import java.util.Arrays;  
 
class GFG{
     
// Function to find the maximum sum of
// MEX of prefix arrays for any
// arrangement of the given array
static void maximumMex(int arr[], int N)
{
     
    // Stores the final arrangement
    int ans[] = new int[2 * N];
 
    // Sort the array in increasing order
    Arrays.sort(ans);
    int j = 0;
     
    // Iterate over the array arr[]
    for(int i = 0; i < N; i++)
    {
        if (i == 0 || arr[i] != arr[i - 1])
        {
            j += 1;
            ans[j] = arr[i];
        }
    }
 
    // Iterate over the array, arr[]
    // and push the remaining occurrences
    // of the elements into ans[]
    for(int i = 0; i < N; i++)
    {
        if (i > 0 && arr[i] == arr[i - 1])
        {
            j += 1;
            ans[j] = arr[i];
        }
    }
 
    // Print the array, ans[]
    for(int i = 0; i < N; i++)
        System.out.print(ans[i] + " ");
}
 
// Driver Code
public static void main (String[] args)
{
     
    // Given array
    int arr[] = { 1, 0, 0 };
 
    // Store the size of the array
    int N = arr.length;
 
    // Function Call
    maximumMex(arr, N);
}
}
 
// This code is contributed by AnkThon
 
 

Python3




# Python3 program for the above approach
 
# Function to find the maximum sum of
# MEX of prefix arrays for any
# arrangement of the given array
def maximumMex(arr, N):
 
    # Stores the final arrangement
    ans = []
 
    # Sort the array in increasing order
    arr = sorted(arr)
 
    # Iterate over the array arr[]
    for i in range(N):
        if (i == 0 or arr[i] != arr[i - 1]):
            ans.append(arr[i])
 
    # Iterate over the array, arr[]
    # and push the remaining occurrences
    # of the elements into ans[]
    for i in range(N):
        if (i > 0 and arr[i] == arr[i - 1]):
            ans.append(arr[i])
 
    # Print the array, ans[]
    for i in range(N):
        print(ans[i], end = " ")
 
# Driver Code
if __name__ == '__main__':
   
    # Given array
    arr = [1, 0, 0 ]
 
    # Store the size of the array
    N = len(arr)
 
    # Function Call
    maximumMex(arr, N)
 
# This code is contributed by mohit kumar 29.
 
 

C#




// C# program for the above approach
using System;
 
class GFG{
     
// Function to find the maximum sum of
// MEX of prefix arrays for any
// arrangement of the given array
static void maximumMex(int []arr, int N)
{
     
    // Stores the final arrangement
    int []ans = new int[2 * N];
 
    // Sort the array in increasing order
    Array.Sort(ans);
    int j = 0;
     
    // Iterate over the array arr[]
    for(int i = 0; i < N; i++)
    {
        if (i == 0 || arr[i] != arr[i - 1])
        {
            j += 1;
            ans[j] = arr[i];
        }
    }
 
    // Iterate over the array, arr[]
    // and push the remaining occurrences
    // of the elements into ans[]
    for(int i = 0; i < N; i++)
    {
        if (i > 0 && arr[i] == arr[i - 1])
        {
            j += 1;
            ans[j] = arr[i];
        }
    }
 
    // Print the array, ans[]
    for(int i = 0; i < N; i++)
        Console.Write(ans[i] + " ");
}
 
// Driver Code
public static void Main (string[] args)
{
     
    // Given array
    int []arr = { 1, 0, 0 };
 
    // Store the size of the array
    int N = arr.Length;
 
    // Function Call
    maximumMex(arr, N);
}
}
 
// This code is contributed by AnkThon
 
 

Javascript




<script>
 
// Javascript program for the above approach
 
// Function to find the maximum sum of
// MEX of prefix arrays for any
// arrangement of the given array
function maximumMex(arr, N)
{
 
    // Stores the final arrangement
    var ans = [];
 
    // Sort the array in increasing order
    arr.sort();
    var i;
    // Iterate over the array arr[]
    for (i = 0; i < N; i++) {
        if (i == 0 || arr[i] != arr[i - 1])
            ans.push(arr[i]);
    }
 
    // Iterate over the array, arr[]
    // and push the remaining occurrences
    // of the elements into ans[]
    for (i = 0; i < N; i++) {
        if (i > 0 && arr[i] == arr[i - 1])
            ans.push(arr[i]);
    }
 
    // Print the array, ans[]
    for (i = 0; i < N; i++)
        document.write(ans[i] + " ");
}
 
// Driver Code
    // Given array
    var arr = [1, 0, 0];
 
    // Store the size of the array
    var N = arr.length;
 
    // Function Call
    maximumMex(arr, N);
 
</script>
 
 
Output
0 1 0 

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



Next Article
Maximum MEX from all subarrays of length K

R

ramandeep8421
Improve
Article Tags :
  • Arrays
  • DSA
  • Mathematical
  • Sorting
  • MEX (Minimal Excluded)
  • prefix
Practice Tags :
  • Arrays
  • Mathematical
  • Sorting

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