Minimum operations for same MEX
Last Updated :
31 Oct, 2023
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 integer 'x' and append it to the chosen array.
Examples:
Input: arr = { {2, 2, 3}, {4, 1, 3}, {3, 1, 2} }
Output: 4
Explanation: 1, 2, 3, 4 can not be the MEX as none of all four is a number that is not present in all the 3 arrays, but 5 is not present in all three so to make 5 as MEX of all three we have to add 1, 4 in the first array and 2 in second and 4 in third after this arrays will look like {2, 2, 3, 1, 4}, {4, 1, 3, 2},
{3, 1, 2, 4}, and their MEX will be 5.
Input: arr = { {1, 2, 2}, {1, 1, 1}, {2, 1, 2} }
Output: 1
Explanation: 3 is the smallest positive number that is not present in all three arrays. So to make 3 as MEX we have to add 2 in the second array and that will take a total of 1 operation.
Approach: To solve the problem follow the below observations:
Observations:
- As we have to find the smallest missing number from all arrays, So we will start with the smallest positive number 1.
- If one is present in at least one of the arrays then this number can not be a number that is missing from all arrays so we have to do operations to add 1 in arrays in which it is not present.
- For step-2 total operation will be the total number of arrays in which 1 is not present.
- Then we will go to the next element which is 2 and do the same operation until we get an element that is not present in the array.
- While doing step-2 to step-4, we will keep updating our number of operations as said in step-3.
- In last, we will return the total number of operations.
Follow the steps to solve the problem:
- First, we will take an ans variable to store the number of operations
- After this, we will take a HashMap for each N array and store the elements present in each array so that we can get the information on whether an element is present in this array or not in O(1) time.
- After this, we will take the number variable which will represent the minimum positive number that is not present in all arrays.
- After this, we have to traverse all arrays until we get an element that is not present in all arrays.
- While traversing we will keep track of the total variable that number is not present in how many arrays.
- If that number is not present in all arrays then the total will be equal to N else it will not.
- If not present in all arrays then we have to return our ans variable
- Else we have to add the number of operations to add this number in which arrays this number is not present.
Below is the implementation for the above approach:
C++
// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
int MexEquality(int N, int M, vector<vector<int> >& Arr)
{
// Variable to store minimum number
// of operations
int ans = 0;
// To store which element is present or not
unordered_map<int, int> mm[N];
// Storing which element is present
for (int i = 0; i < N; i++) {
for (auto x : Arr[i]) {
mm[i][x] = 1;
}
}
// To start with minimum positive number as
// explained in explanation
int number = 1;
// Until we got our answer
while (true) {
// i for iteration and
// total, for arrays which do not
// contain number
int i, total = 0;
for (i = 0; i < N; i++) {
if (mm[i][number] == 0) {
total++;
}
}
// If all arrays do not contain number
if (total == N)
return ans;
// Else add that element in all those
// array and increase operations
ans += total;
number++;
}
return ans;
}
// Drivers code
int main()
{
int N, M;
vector<vector<int> > Arr{ { 1, 2, 2 },
{ 1, 1, 1 },
{ 2, 1, 2 } };
N = Arr.size();
M = Arr[0].size();
// Functional call
cout << MexEquality(N, M, Arr);
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
public class GFG {
static int MexEquality(int N, int M, List<List<Integer>> Arr) {
// Variable to store the minimum number of operations
int ans = 0;
// To store which element is present or not
HashMap<Integer, Integer>[] mm = new HashMap[N];
for (int i = 0; i < N; i++) {
mm[i] = new HashMap<>();
for (int x : Arr.get(i)) {
mm[i].put(x, 1);
}
}
// To start with the minimum positive number as explained in the explanation
int number = 1;
// Until we get our answer
while (true) {
// 'i' for iteration and 'total' for arrays which do not contain the number
int i, total = 0;
for (i = 0; i < N; i++) {
if (!mm[i].containsKey(number)) {
total++;
}
}
// If all arrays do not contain the number
if (total == N)
return ans;
// Else add that element in all those arrays and increase operations
ans += total;
number++;
}
}
public static void main(String[] args) {
int N, M;
List<List<Integer>> Arr = new ArrayList<>();
Arr.add(Arrays.asList(1, 2, 2));
Arr.add(Arrays.asList(1, 1, 1));
Arr.add(Arrays.asList(2, 1, 2));
N = Arr.size();
M = Arr.get(0).size();
// Functional call
System.out.println(MexEquality(N, M, Arr));
}
}
Python3
# Function to calculate the minimum number of operations
def MexEquality(N, M, Arr):
ans = 0
mm = [{} for _ in range(N)] # Create a list of dictionaries for each row
# Fill in the dictionaries with elements from the matrix
for i in range(N):
for x in Arr[i]:
mm[i][x] = 1
number = 1 # Start with the minimum positive number
while True:
i, total = 0, 0
# Count the number of arrays that do not contain the current number
for i in range(N):
if mm[i].get(number, 0) == 0:
total += 1
# If all arrays do not contain the current number, return the answer
if total == N:
return ans
ans += total # Add the count of arrays that don't contain the number to the answer
number += 1 # Move to the next number
return ans
# Driver code
if __name__ == "__main__":
Arr = [[1, 2, 2],
[1, 1, 1],
[2, 1, 2]]
N = len(Arr) # Number of rows
M = len(Arr[0]) # Number of columns
# Function call and output the result
print(MexEquality(N, M, Arr))
#This code is contributed by chinmaya121221
C#
using System;
using System.Collections.Generic;
class Program
{
static int MexEquality(int N, int M, List<List<int>> Arr)
{
// Variable to store minimum number
// of operations
int ans = 0;
// To store which element is present or not
Dictionary<int, int>[] mm = new Dictionary<int, int>[N];
// Storing which element is present
for (int i = 0; i < N; i++)
{
mm[i] = new Dictionary<int, int>();
foreach (int x in Arr[i])
{
mm[i][x] = 1;
}
}
// To start with minimum positive number as
// explained in explanation
int number = 1;
// Until we got our answer
while (true)
{
// i for iteration and
// total, for arrays which do not
// contain number
int total = 0;
for (int i = 0; i < N; i++)
{
if (!mm[i].ContainsKey(number))
{
total++;
}
}
// If all arrays do not contain number
if (total == N)
{
return ans;
}
// Else add that element in all those
// array and increase operations
ans += total;
number++;
}
//return ans;
}
// Drivers code
static void Main(string[] args)
{
int N, M;
List<List<int>> Arr = new List<List<int>>()
{
new List<int>() { 1, 2, 2 },
new List<int>() { 1, 1, 1 },
new List<int>() { 2, 1, 2 }
};
N = Arr.Count;
M = Arr[0].Count;
Console.WriteLine(MexEquality(N, M, Arr));
}
}
JavaScript
function MexEquality(N, M, Arr) {
// Variable to store the minimum number of operations
let ans = 0;
let mm = new Array(N);
for (let i = 0; i < N; i++) {
// To store which element is present or not
mm[i] = new Map();
for (let x of Arr[i]) {
mm[i].set(x, 1);
}
}
// To start with the minimum positive number as explained in the explanation
let number = 1;
// Until we get our answer
while (true) {
// 'i' for iteration and 'total' for arrays which do not contain the number
let total = 0;
for (let i = 0; i < N; i++) {
if (!mm[i].has(number)) {
total++;
}
}
// If all arrays do not contain the number
if (total === N) {
return ans;
}
// Else add that element in all those arrays and increase operations
ans += total;
number++;
}
}
let N, M;
let Arr = [];
Arr.push([1, 2, 2]);
Arr.push([1, 1, 1]);
Arr.push([2, 1, 2]);
N = Arr.length;
M = Arr[0].length;
// Functional call
console.log(MexEquality(N, M, Arr));
Time Complexity: O(N*M)
Auxiliary Space: O(N*M)
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