How to Set Mismatch() in C++ Program ?

  C & C ++ Interview Q&A

Dear readers, today read in this article how to set () mismatch in C ++ program?

If there is a set S which is basically a number from 1 to n. But unfortunately, due to some error, one number in the set was repeated in the other number in the set, resulting in the repetition of one number and the loss of another number.

Now if we have an array called a digit that is representing the data state of this set after an error. Our task is to make the number occur twice and then find the number that is missing. Return the result as an array.

Therefore, if the input is like [1,2,3,4,4,6], the output will be [4,5]

Example for Set Mismatch in C++Output

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class setMismatchProg{
public:
   vector<int> findErrorNums(vector<int>& A) {
      vector<int> v(2);
      long long int s1 = accumulate(A.begin(), A.end(), 0);
      int n = A.size();
      long long int exp_sum = (n * (n + 1)) / 2;
      for (int i = 0; i < n; i++) {
         if (A[abs(A[i]) - 1] > 0) {
            A[abs(A[i]) - 1] = -A[abs(A[i]) - 1];
         }
         else {
            v[0] = abs(A[i]);
         break;
         }
      }
      v[1] = v[0] - (s1 - exp_sum);
      return v;
   }
};
main(){
   setMismatchProg ob;
   vector<int> v = {1,2,3,4,4,6};
   print_vector(ob.findErrorNums(v));
}

Output

[4, 5, ]

LEAVE A COMMENT