Find missing number in another array which is shuffled copy in C++


Suppose, we have two arrays A and B, the array A has n elements. The second array B has all the elements of A, but they are shuffled and one element is removed. We have to find the missing elements. So if A = [4, 8, 1, 3, 7], and B = [7, 4, 3, 1], the output is 8.

This can be solved using XOR trick. The combined occurrence of each element is twice, one in A, and other in B, except one element which only has a single occurrence in A. As we know that x XOR x = 0, so if we perform XOR in elements of both the arrays. The result will be missing number.

Example

 Live Demo

#include<iostream>
using namespace std;
int FindMissingElement(int A[], int B[], int n) {
   int min_element = 0;
   for (int i = 0; i < n; i++)
   min_element = min_element ^ A[i];
   for (int i = 0; i < n - 1; i++)
   min_element = min_element ^ B[i];
   return min_element;
}
int main() {
   int A[] = {4, 8, 1, 3, 7};
   int B[] = {7, 4, 3, 1};
   int n = sizeof(A) / sizeof(A[0]);
   cout << "Missing element: " << FindMissingElement(A, B, n);
}

Output

Missing element: 8

Updated on: 18-Dec-2019

230 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements