
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Minimum Operations to Make the MEX of a Given Set Equal to X in C++
Problem statement
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
Example
If n = 5 and x = 3 and array is {0, 4, 5, 6, 7} then we require minimum 2 operations
Algorithm
- 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.
Example
#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; }
Output
When you compile and execute above program. It generates following output −
Minimum required operations = 2
Advertisements