Set Mismatch in C++

C++Server Side ProgrammingProgramming

Suppose there is a set S that is originally containing numbers from 1 to n. But unfortunately, due to some error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.

Now if we have an array called nums that is representing the data status of this set after the error. Our task is to find the number occurs twice and then find the number that is missed. return the results in the form of an array.

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

To solve this, we will follow these steps −

• Define an array v of size 2

• s1 := sum of all numbers of A

• n := size of A

• exp_sum := (n * (n + 1))

• for initialize i := 0, when i < n, update (increase i by 1), do −

• if A[|A[i]| - 1] > 0, then −

• A[|A[i]| - 1] = -A[|A[i]| - 1]

• Otherwise

• v[0] := |A[i]|

• Come out from the loop

• v[1] := v[0] - (s1 - exp_sum)

• return v

Example

Let us see the following implementation to get better understanding −

Live Demo

#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 Solution {
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(){
Solution ob;
vector<int> v = {1,2,3,4,4,6};
print_vector(ob.findErrorNums(v));
}

Input

{1,2,3,4,4,6}

Output

[4, 5, ]
Published on 11-Jun-2020 15:41:54