I have three one-dimensional arrays. The task is to store the numbers which exist in each of the three arrays in a forth array. Here is my solution which as you see isn’t correct. I’m also interested in a faster algorithm if possible because it’s O(N3) difficulty.
#include <stdio.h>
main(){
int a[5]={1,3,6,7,8};
int b[5]={2,5,8,7,3};
int c[5]={4,7,1,3,6};
int i,j,k;
int n=0;
int d[5];
for(k=0; k<5; k++){
for(j=0; j<5; j++){
for(i=0; i<5; i++){
if(a[i]==b[j] && b[j]==c[k])
{d[n]=a[i];
n++;}
else
d[n]=0;
}}}
//Iterate over the new array
for(n=0;n<5;n++)
printf("%d\n",d[n]);
return 0;
}
One way to improve to
O(n log n)is to sort all three arrays first.Then use three pointers one for each array. You always move the one that points to the lowest value and after every such move check whether the three values are the same.
To improve even further you can use hashtable.
Iterate through the first array and put it’s values in a hashtable as keys.
Then iterate through the second array and every time when the value exists as a key in the first hashtable, put it in a second one.
Finally iterate over the third array and if a value exists in the second hashtable as a key store it in the forth array. This is
O(n)assuming the hashtable operations areO(1).