Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
AMZ 10
------
Input: two arrays
Output: boolean stating their equality
Assumptions:
- Equal in length
- Equal in values
- What if values are custom classes?
- Trust that their equality function works?
- Are the objects comparable?
Braintorm:
1.
- If length is equal
- Sort both arrays, then compare each element
O(nlogn) time, O(1) space
2.
- Add first array to hashMap
- Check if each element from 2nd array exists in hashMap, if it does, remove from hashMap
- If hashMap is empty at the end, arrays are equal
O(n) time, O(n) space
public boolean areEqual(T[] a, T[] b) {
if(a.length != b.length)
return false;
if(!a.getClass().equals(b.getClass())
return false;
Arrays.sort(a /* May need to pass comparator */);
Arrays.sort(b /* May need to pass comparator */);
for(int i = 0; i < a.length; i++) {
if(!a[i].equals(b[i]))
return false;
//Can use a[i].compareTo(b[i]) != 0 if that's implemented
//Or whichever equality/comparison function is appropriate
}
return true;
}
class Test
{
public static void main(String[] args)
{
int[] arr1 = {1,2,3,4};
int[] arr2 = {1,2,3,4};
boolean flag = true;
for(int i=0; i < arr1.length; i++)
{
if(arr1[i] != arr2[i])
{
flag = false;
}
}
if(flag)
System.out.println("Arrays are equal");
else
System.out.println("Arrays are not equal");
}
}
I guess we can use XOR operation here...
--First perform XOR inside each of the arrays independently---o(n)
--Then perform a XOR of the result of the two.
If the final result is zero--this means the arrays are equal.
int xor1=0,xor2=0;
for(int i=0;i<arr1.length;i++){
xor1^=arr1[i];
}
for(int j=0;j<arr2.length;j++){
xor2^=arr2[j];
}
int xor = xor1^xor2;
if(xor>0) printf("Arrays are not equal");
Your solution is good however you can mention some other solutions like:
- ahmad.m.bakr June 03, 20131- If equal arrays mean they are identical (i.e they have the same numbers at the same positions) then it can be done in O(n) and O(1) space just by looping in one of the arrays and compare each element to its corresponding element in the other array.
2- If you can know the range of the numbers in the array (like numbers are from 0 to N-1) then you will need an additional array of the same size instead of a hash table which will give you a faster access. By the additional array you can loop on one array, count the occurrences of each element then loop on the second array and subtract the occurrences. If the additional array has zero at each position then they are equal otherwise they are not. This requires four passes (initialize the temp array, count the occurrences of the first array, subtract the occurrences of the second array and finally check the temp array).
3- You can sort both arrays and apply approach #1 O(N log N)
4- You can use a hash table just like you did.
Ofcourse a comparison of the lengths of the both arrays can save much effort.
Hope that helps you .