Partition the given array in two parts to make the MEX of both parts same
Last Updated :
05 Apr, 2022
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
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
Maximize partitions that if sorted individually makes the whole Array sorted
Given an array arr[]. The task is to divide arr[] into the maximum number of partitions, such that, those partitions if sorted individually make the whole array sorted.Examples:Input: arr[] = { 28, 9, 18, 32, 60, 50, 75, 70 }Output: 4Explanation: Following are the partitions in which the array is di
5 min read
Count number of ways array can be partitioned such that same numbers are present in same subarray
Given an array A[] of size N. The Task for this problem is to count several ways to partition the given array A[] into continuous subarrays such that the same integers are not present in different subarrays. Print the answer modulo 109 + 7. Examples: Input: A[] = {1, 2, 1, 3} Output: 2Explanation: T
11 min read
Minimum operations to make counts of remainders same in an array
Given an array arr[] of N integers and an integer M where N % M = 0. The task is to find the minimum number of operations that need to be performed on the array to make c0 = c1 = ..... = cM - 1 = N / M where cr is the number of elements in the given array having remainder r when divided by M. In eac
7 min read
Minimize Array partitions such that an element is repeated atmost once in each partition
Given an array arr[] consisting of positive integers. The task is to minimize the contiguous groups formed if each element from arr[] can be a part of atmost one group, and a number can be repeated only once. Examples: Input: arr[] = {1, 2, 1, 1, 1, 1, 1, 2, 3}Output: { {1, 2, 1}, {1, 1}, {1, 1, 2,
6 min read
Partition the array into three equal sum segments
Given an array of n integers, we have to partition the array into three segments such that all the segments have an equal sum. Segment sum is the sum of all the elements in the segment. Examples: Input : 1, 3, 6, 2, 7, 1, 2, 8 Output : [1, 3, 6], [2, 7, 1], [2, 8] Input : 7, 6, 1, 7 Output : [7], [6
12 min read
Number of K's such that the given array can be divided into two sets satisfying the given conditions
Given an array arr[] of size N. The task is to find the number of K's such that the array can be divided into two sets containing equal number of elements if elements less than K are in one set and the rest of them are in the other set. Note: N is always even. Examples: Input: arr[] = {9, 1, 4, 4, 6
4 min read
Split the Array in two parts such that maximum product is minimized
Given an array of integers, arr[] of size N (<=16), the task is to partition the array into 2 parts such that the maximum product of the 2 halves is minimized. Find the minimized maximum product of the half. If the array is empty, print -1. Examples: Input: arr[] = {3, 5, 7}Output: 15Explanation:
7 min read
Partition an array of non-negative integers into two subsets such that average of both the subsets is equal
Given an array of size N. The task is to partition the given array into two subsets such that the average of all the elements in both subsets is equal. If no such partition exists print -1. Otherwise, print the partitions. If multiple solutions exist, print the solution where the length of the first
14 min read
Partition Array into two Arrays of equal size to Minimize Sum Difference
Given an integer array of size 2*n, partition the array into two arrays of equal length such that the absolute difference between the sums of these two arrays is minimum. Return this minimum difference. To partition the array, allocate each element to one of two arrays. Examples :Input: arr[] = {7,
15+ min read