Given an array of size N-1 such that it only contains distinct integers in the range of 1 to N. Find the missing element.
This has a simple approach we can sum all numbers from 1 to N then subtract from the sum of the array we will get the missing number.
#include <bits/stdc++.h>
using namespace std;
class Solution{
public:
int MissingNumber(vector<int>& array, int n) {
// Your code goes here
long long int sum=(n*(n+1))/2;
long long sum2=0;
for(auto x:array)
{
sum2+=x;
}
return (int)(sum-sum2);
}
};
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> array(n - 1);
for (int i = 0; i < n - 1; ++i) cin >> array[i];
Solution obj;
cout << obj.MissingNumber(array, n) << "\n";
}
return 0;
}