Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinguishing extra element from two arrays?

One of my friend was asked this question in an interview -

  • You have given two integer arrays each of size 10.
  • Both contains 9 equal elements (say 1 to 9)
  • Only one element is different.

How will you find the different element? What are different approaches you can take?

One simple but lengthy approach would be - sort both arrays,go on comparing each element,on false comparison, you'll get your result.

So what are different approaches for this? Specify logic as its expected in an interview. Not expecting a particular code in a specific language. Pseudo code will suffice.

(Please submit one approach per answer)

My purpose of asking this question is, its OK when array sizes are small.But when array size increases, you must think of a very efficient n faster way.Its never desirable to use comparisons in such case.

like image 825
Pale Blue Dot Avatar asked Oct 19 '09 18:10

Pale Blue Dot


People also ask

How do I find the extra element in two arrays?

Efficient approach: If all the elements of the A[] and B[] are XORed together then every element of A[] will give 0 with its occurrence in B[] and the extra element say X when XORed with 0 will give (X XOR 0) = X which is the result. Below is the implementation of the above approach: C++ Java.

How do I compare two arrays of elements?

Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.

How do you compare the length of two arrays?

equals() Method. Java Arrays class provides the equals() method to compare two arrays. It iterates over each value of an array and compares the elements using the equals() method.

Can 2 arrays be equal?

Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. Also, two array references are considered equal if both are null.


1 Answers

If you need this to scale, then I would use one of the many Set implementations in the world. For example, Java's HashSet.

Throw all of the first array in the Set. Then, for each member of the second array, if it is contained in the Set, remove it; otherwise mark it as Unique #2. After this procedure, the last remaining member of the Set is Unique #1.

I'd probably do it this way, even on an interview, and even for simple ten-element arrays. Life is too short to spend trying to find the clever way to scale a wall when there's a perfectly good door in it.

like image 66
jprete Avatar answered Oct 06 '22 12:10

jprete