Google Interview Question
Software Engineer / Developersbool hasSame(int* a, int* b, int la, int lb){
sort(a, la);
sort(b, lb);
int i=0, j=0;
while(i<la && j<lb){
if(a[i] == b[j]) return true;
if(a[i] > b[j]) j++;
else i++;
}
return false;
}
void sort(int* a, int la){
int k = rand(la); // from 0 to la-1
int spliter = a[k];
int i=0, j=la-1;
while(i<j){
if(a[i]<=a[k]) i++;
if(a[j]>a[k]) i--;
if(a[i]>a[k] && a[j]<=a[k]){
int swap = a[i];
a[i] = a[j];
a[j] = swap;
}
}
sort(a,i);
sort(a+i, la-i);
}
You can exit earlier and no need to go through hash at the end:
Just add "if (hash[value] != 0) return false"
Then you can delete
" for(var key in hash) {
if(hash[key] != 0) {
return false;
}
} "
We can permit this because the 2 arrays got the same length and because you did
"if(typeof hash[value] == 'undefined') {"
This is wrong.
a[] = {0, 0}
b[] = {1, 1}
XOR of a and b would be zero but they are not the same.
Following two steps, both must be true
1)find sum of individual arrays, both sums must be equal
2)Now xor both the arrays, xor must be 0
If both above conditions are satisfied,arrays contain same elements
Complexity: O(n)
Following THREE steps, all must be true
1)find sum of individual arrays, both sums must be equal
2)find product of both arrays,product must also be equal
3)Now xor both the arrays, xor must be 0
If ALL above conditions are satisfied,arrays contain same elements
Complexity: O(n)
Sorry ,but this is the final algo
Following Four steps, all must be true
1)find sum of individual arrays, both sums must be equal
2)find product of both arrays,product must also be equal
3)Now xor both the arrays, xor must be 0
4)And both arrays must contain the same number of elements
If ALL above conditions are satisfied,arrays contain same elements
Complexity: O(n)
Method 1: hashtable
- eboyGTK April 15, 2012space complexity: O(n). time complexity: O(n)
Method 2: sort then scan
(1) sort two arrays, O(nlogn + mlogm)
(2) use to pointers to scan the two arrays. when finding two same values, stop and return. O(n+m)
time complexity: O(nlogn+mlogm)