Partition the given array in two parts to make the MEX of both parts same
Last Updated :
23 Jul, 2025
Given an array arr[] containing N integers where 0 ≤ A[ i ] ≤ N, the task is to divide the array into two equal parts such that the MEX of both the parts are the same, otherwise print -1.
Note: The MEX (minimum excluded) of an array is the smallest non-negative integer that does not exist in the array.
Examples:
Input: N = 6, arr[] = {1, 6, 2, 3, 5, 2}
Output:
0
1 2 5
2 3 6
Explanation: After dividing the given array into {1, 2, 5} and {2, 3, 6}, MEX of both array is equal( i. e MEX = 0)
Input: N = 4, arr[] = {0, 0, 1, 2}
Output: -1
Explanation: Not possible to divide an array into two different array
Intuition: As mentioned, MEX is the smallest non-negative integer that does not belong to the array. So any non-negative smallest number which is not present in the given array can become the MEX for both output arrays.
To make an integer X, MEX for both arrays, all elements less than X must present at least once in both the output array.
For Example:
Array = [1, 4, 2, 4, 2, 1, 1]
Then divide the array into [1, 1, 2, 4] and [1, 2, 4]
If any element less than X is present in the given array only once, then it is not possible to divide the given array into two arrays of equal MEX.
Example:
Array = [1, 2, 3, 4, 4, 2, 1]
In this example, 3 is only present 1 time in given array so if we try to divide it into 2 array, then MEX of both array is not equal.
[1, 2, 3, 4] : MEX = 5
[1, 2, 4] : MEX = 3
Approach: The solution to the problem is based on the concept of hashmap. Follow the steps mentioned below:
- Create a hash map to check whether any unique element is present in the array or not.
- Iterate from 0 to N and in each iteration check
- If the frequency of that element is 1, then it is not possible to divide the array into two such that their MEX should be equal
- If the frequency of that element is 0, then we can divide the array.
- If the frequency of that element is more than 1, then check for the next element.
- Sort the given array and divide the array according to its even or odd index, so that if any element is present 2 or more than 2 times in the array then after dividing both output array consists at least 1 time that elements to maintain equal MEX.
- Print both the arrays.
Below is the code implementation:
C++
// C++ code to implement the above approach:
#include <bits/stdc++.h>
using namespace std;
// Function to find the
// Least common missing no.
void MEX_arr(int* A, int N)
{
unordered_map<int, int> mp;
bool status = true;
// Push all array elements
// Into unordered_map
for (int i = 0; i < N; i++) {
mp[A[i]]++;
}
// Check any unique element is present
// In array or any element
// Which is not array;
for (int i = 0; i <= N; i++) {
if (mp[i] == 0) {
cout << i << "\n";
break;
}
if (mp[i] == 1) {
status = false;
break;
}
}
if (status == true) {
// Sort the array
sort(A, A + N);
int A1[N / 2], A2[N / 2];
// Push all elements at even index
// in first array and at odd index
// into another array
for (int i = 0; i < N / 2; i++) {
A1[i] = A[2 * i];
A2[i] = A[2 * i + 1];
}
// Print both the arrays
for (int i = 0; i < N / 2; i++) {
cout << A1[i] << " ";
}
cout << "\n";
for (int i = 0; i < N / 2; i++) {
cout << A2[i] << " ";
}
}
// If not possible to divide
// into two array, print -1
else
cout << -1;
}
// Driver code
int main()
{
int N = 6;
int arr[N] = { 1, 6, 2, 3, 5, 2 };
unordered_map<int, int> mp;
// Function call
MEX_arr(arr, N);
return 0;
}
Java
// Java code to implement the above approach
import java.io.*;
import java.util.*;
class GFG
{
// Function to find the
// Least common missing no.
public static void MEX_arr(int A[], int N)
{
HashMap<Integer, Integer> mp = new HashMap<>();
boolean status = true;
// Push all array elements
// Into HashMap
for (int i = 0; i < N; i++) {
if (mp.get(A[i]) != null)
mp.put(A[i], mp.get(A[i]) + 1);
else
mp.put(A[i], 1);
}
// Check any unique element is present
// In array or any element
// Which is not array;
for (int i = 0; i <= N; i++) {
if (mp.get(i) == null) {
System.out.println(i);
break;
}
if (mp.get(i) == 1) {
status = false;
break;
}
}
if (status == true) {
// Sort the array
Arrays.sort(A);
int A1[] = new int[N / 2];
int A2[] = new int[N / 2];
// Push all elements at even index
// in first array and at odd index
// into another array
for (int i = 0; i < N / 2; i++) {
A1[i] = A[2 * i];
A2[i] = A[2 * i + 1];
}
// Print both the arrays
for (int i = 0; i < N / 2; i++) {
System.out.print(A1[i] + " ");
}
System.out.println();
for (int i = 0; i < N / 2; i++) {
System.out.print(A2[i] + " ");
}
}
// If not possible to divide
// into two array, print -1
else
System.out.print(-1);
}
public static void main(String[] args)
{
int N = 6;
int arr[] = { 1, 6, 2, 3, 5, 2 };
// Function call
MEX_arr(arr, N);
}
}
// This code is contributed by Rohit Pradhan.
Python3
# python3 code to implement the above approach:
# Function to find the
# Least common missing no.
def MEX_arr(A, N):
mp = {}
status = True
# Push all array elements
# Into unordered_map
for i in range(0, N):
mp[A[i]] = mp[A[i]]+1 if A[i] in mp else 1
# Check any unique element is present
# In array or any element
# Which is not array;
for i in range(0, N+1):
if (not i in mp):
print(i)
break
elif (mp[i] == 1):
status = False
break
if (status == True):
# Sort the array
A.sort()
A1, A2 = [0 for _ in range(N // 2)], [0 for _ in range(N // 2)]
# Push all elements at even index
# in first array and at odd index
# into another array
for i in range(0, N//2):
A1[i] = A[2 * i]
A2[i] = A[2 * i + 1]
# Print both the arrays
for i in range(0, N//2):
print(A1[i], end=" ")
print()
for i in range(0, N // 2):
print(A2[i], end=" ")
# If not possible to divide
# into two array, print -1
else:
print(-1)
# Driver code
if __name__ == "__main__":
N = 6
arr = [1, 6, 2, 3, 5, 2]
# unordered_map<int, int> mp;
# Function call
MEX_arr(arr, N)
# This code is contributed by rakeshsahni
C#
// C# code to implement the above approach:
using System;
using System.Collections.Generic;
class GFG
{
// Function to find the
// Least common missing no.
static void MEX_arr(int []A, int N)
{
Dictionary<int, int> mp =
new Dictionary<int, int>();
bool status = true;
// Push all array elements
// Into unordered_map
for (int i = 0; i < N; i++) {
if(mp.ContainsKey(A[i])) {
mp[A[i]] = mp[A[i]] + 1;
}
else {
mp.Add(A[i], 1);
}
}
// Check any unique element is present
// In array or any element
// Which is not array;
for (int i = 0; i <= N; i++) {
if (!mp.ContainsKey(i)) {
Console.WriteLine(i);
break;
}
if (mp[i] == 1) {
status = false;
break;
}
}
if (status == true) {
// Sort the array
Array.Sort(A);
int []A1 = new int[N / 2];
int []A2 = new int[N / 2];
// Push all elements at even index
// in first array and at odd index
// into another array
for (int i = 0; i < N / 2; i++) {
A1[i] = A[2 * i];
A2[i] = A[2 * i + 1];
}
// Print both the arrays
for (int i = 0; i < N / 2; i++) {
Console.Write(A1[i] + " ");
}
Console.WriteLine();
for (int i = 0; i < N / 2; i++) {
Console.Write(A2[i] + " ");
}
}
// If not possible to divide
// into two array, print -1
else
Console.Write(-1);
}
// Driver code
public static void Main()
{
int N = 6;
int []arr = { 1, 6, 2, 3, 5, 2 };
// Function call
MEX_arr(arr, N);
}
}
// This code is contributed by Samim Hossain Mondal.
JavaScript
<script>
// JavaScript code for the above approach
// Function to find the
// Least common missing no.
function MEX_arr(A, N) {
let mp = new Map();
var status = true;
// Push all array elements
// Into unordered_map
for (let i = 0; i < N; i++) {
if (!mp.has(A[i])) {
mp.set(A[i], 1);
}
else {
mp.set(A[i], mp.get(A[i]) + 1)
}
}
// Check any unique element is present
// In array or any element
// Which is not array;
for (let i = 0; i <= N; i++) {
if (!mp.has(i)) {
document.write(i + '<br>')
break;
}
else if (mp.get(i) == 1) {
status = false;
break;
}
}
if (status == true) {
// Sort the array
A.sort(function (a, b) { return a - b })
let A1 = new Array(Math.floor(N / 2));
let A2 = new Array(Math.floor(N / 2));
// Push all elements at even index
// in first array and at odd index
// into another array
for (let i = 0; i < Math.floor(N / 2); i++) {
A1[i] = A[2 * i];
A2[i] = A[2 * i + 1];
}
// Print both the arrays
for (let i = 0; i < N / 2; i++) {
document.write(A1[i] + ' ')
}
document.write('<br>')
for (let i = 0; i < N / 2; i++) {
document.write(A2[i] + ' ')
}
}
// If not possible to divide
// into two array, print -1
else
document.write(-1)
}
// Driver code
let N = 6;
let arr = [1, 6, 2, 3, 5, 2];
// Function call
MEX_arr(arr, N);
// This code is contributed by Potta Lokesh
</script>
Time Complexity: O(N * log(N))
Auxiliary space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem