This post is completed by 9 users

  • 4
Add to List

Find an extra element in two almost similar arrays

Given two arrays where the second array has all the elements from the first array and one extra element. 

Example: 

arrA = [1, 4, 2, 5, 7]
arrB = [1, 2, 4, 1, 7, 5]
Output: 1

arrA = [1, 8, 2, 0]
arrB = [1, 8, 4, 2, 0]
Output: 4

Solution:

This problem can be solved in many ways, for instance, we can add both the arrays separately and then take a difference between those, this difference will be caused by that extra element in the array.

A better solution would be taking an XOR of both the arrays since we know A XOR A = 0 so all the elements which are present in both the arrays will become 0 when taking XOR and the only element will remain, the extra element in one of the arrays. Below is the code for XOR logic 

Code:


Output:

Array A: [3, 4, 5, 2, 9, 6]
Array B: [4, 3, 2, 9, 5, 7, 6]
Extra Element: 7