Find Missing Number (Amazon SDE)
Problem - You are given an array from 1 to n, such that all numbers are present except 'x'. Find 'x'
Approach - We know that the sum of all numbers from 1 to n is n(n+1)/2, If we know this value, then we can easily delete the sum of all the elements except x to find x.
Code -
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n; cin>>n;
int sum_of_n = (n*(n+1))/2;
int arr[n];
int sum_of_arr;
for(int i=0;i<n;i++)
{
cin>>arr[i];
sum_of_arr+=arr[i];
}
int x= sum_of_arr - sum_of_n;
cout<<x;
return 0;
}