Hi,

I was told to write an algorithm as following

There are three arrays A[],B[],C[] of same size N.Find out all possible (i,j,k) such that A[i]+B[j]=C[k].The maximum allowed time complexity is O(N^{2}).Following is the algorithm I wrtten for O(N^{2})

Code:

#include<stdio.h>
#define MAX 1000
struct sum
{
int result;
int i;
int j;
};
int main()
{
struct sum sum_array[MAX];
int n=4;
int a[] = {4,1,2,5};
int b[] = {1,7,6,0};
int c[] = {11,3,8,2};
int k;
int i,j;
for(i=0;i<MAX;i++)
sum_array[i].result=-1;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
sum_array[a[i]+b[j]].result=a[i]+b[j];
sum_array[a[i]+b[j]].i=i;
sum_array[a[i]+b[j]].j=j;
}
}
for(k=0;k<n;k++)
{
if(sum_array[c[k]].result==c[k])
{
printf("<i,j,k> = <%d,%d,%d>\n",sum_array[c[k]].i,sum_array[c[k]].j,k);
}
}
return 0;
}

My question is how to do it faster ? Any O(N*logN) or better algorithm for this ?

Regards,

Arka