Interview Question
Software Engineer / Developerso Create a two dimensional array A [0..x][0..N]
o Fill array A as follows
A[i][m] = 1, if array t[i] is present in the array[m]. Otherwise A[i][m] = 0.
o Create an array sum[0..N]. sum [j] = Sum of all values A[0..x][j].
o Now traverse through sum to find the largest value. If there are multiple of them, then choose the first one.
o Time complexity is O(x * N).
Well, the complexity is O(x*N) no matter what the matrix contains. what if the matrix is sparse? i.e. you don't have the check every element?
what we want to find is the array k'th from N given arrays which contains most of the elements.
An alternative solution whose worst case is O(x*N) but a lot faster for sparse matrix:
1. Create x arrays containing the values
2. Create a count array 'C' of size N.
3. for every element in the test array 't', access the x arrays and increment the count in array 'C'.
Ex:
given 5 arrays containing elements 1 to 9
arr1: 1,5,3,2
arr2: 2,8,3,4
arr3: 4,6,2,7,1
arr4: 5,1,4
arr5: 7,8,9
testArray: 2,4,6
1. create 9 arrays
x1 x2 x3 x4 x5 x6 x7 x8 x9
1 1 1 2 1 3 3 2 5
3 2 2 3 4 5 5
4 3 4
2. create count array C of size N: [0,0,0,0,0]
3. for each element in test array count.
for first element '2'. access x2. increment C[x2[...]] --> C: [1,1,1,0,0]
next element '4', access x4 increment C[x4[...]] --> C: [1,2,2,1,0]
next element '6', access x6 increment C[x6[...]] --> C: [1,2,3,1,0]
max(C) --> 3 i.e. 'arr3' is the closest to test array which is true
so, in this case we are only accessing 7 elements from the 'x' arrays
if we do a two dimensional matrix approach then we would access 9*5 = 45 elements
Thanks.
I would say hash map.
- Rayden December 07, 2010