One of my friend was asked this question in an interview -
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With