Amazon Interview Question

How will you check to see if two integer arrays have any common elements?

Interview Answers

Anonymous

Feb 10, 2012

Soln1: 1) Sort array1 and array2 2) Follow the implementation by @solutionYoda. Soln2: 1) Store the array1 value in hashmap 2) Iterate the array2 and check if the element is existing in hashmap. If yes then print the value. or you can change the value of the map.put(key,"true"). Time complexity O(m) for array1 to put in hashmap O(n) for array2 and check it in hashmap. plus some operation to change the value for matched value. Space Complexity O(m) for the array1. Always choose smaller array to store the value in hashmap.

2

Anonymous

Dec 20, 2011

My solution was this...If the arrays are A, B. Load the data in array A into a Hash Table (excluding any duplicates in the array) Now take every element in array B and try to look up the hash table if there are any entries...if there are any collisions, we can say that, they have common elements. I know this can be done in much better ways which I dont know :)

Anonymous

Jan 18, 2012

@SolutionYoda Your solution would be correct if the arrays are sorted...

Anonymous

Jan 9, 2012

The question essentially is asking you to find the intersection between two arrays: You can traverse the two arrays in O(N) then simply return the common elements (although thats not asked). int i = 0; j = 0; while(i arr2[j]) { j++; } else { i++ } return vector;