- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 {0, 2, 4} is 1 and the MEX of the set {1, 2, 3} is 0

If n = 5 and x = 3 and array is {0, 4, 5, 6, 7} then we require minimum 2 operations

- The approach is to see that in the final set all the elements less than x should exist, x shouldn’t exist and any element greater than x doesn’t matter.
- So, we will count the number of elements less than x that don’t exist in the initial set and add this to the answer.
- If x exists we will add 1 to the answer because x should be removed.

#include <iostream> using namespace std; int getMinOperations(int *arr, int n, int x) { int k = x, i = 0; while (n--) { if (arr[n] < x) { --k; } if (arr[n] == x) { ++k; } } return k; } int main() { int arr[] = {0, 4, 5, 6, 7}; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; cout << "Minimum required operations = " << getMinOperations(arr, n, x) << endl; return 0; }

When you compile and execute above program. It generates following output −

Minimum required operations = 2

- Related Questions & Answers
- Minimum number of given operations required to make two strings equal using C++.
- Minimum operations required to make all the array elements equal in C++
- Minimum operations of given type to make all elements of a matrix equal in C++
- Minimum move to end operations to make all strings equal in C++
- Program to find minimum operations to make array equal using Python
- Minimum operations to make XOR of array zero in C++
- Minimum Swaps to Make Strings Equal in C++
- Minimum delete operations to make all elements of array same in C++.
- Program to find minimum operations to make the array increasing using Python
- Minimum operations to make GCD of array a multiple of k in C++
- Minimum number of moves to make all elements equal using C++.
- Minimum Flips to Make a OR b Equal to c in C++
- Find minimum operations needed to make an Array beautiful in C++
- Find minimum number of merge operations to make an array palindrome in C++
- Minimum operations required to set all elements of binary matrix in C++

Advertisements