I have two sets of elements and I want an optimal algorithm to find their differences or in math form: A U B – A ∩ B
One way I thought is
Bfound=0;
for (1->Na,i)
{
flag=0;
for (1->Nb,j)
{
if(A[i]==B[j])
{
flag=1;
Bfound[j]=1;
}
}
if (flag==0)
print A[i]
}
for(1->Nb,i)
{
if(Bfound[i]==0)
print B[i]
}
Is this optimal?
To answer your question – no, this is not optimal. The complexity of your solution is O(nm) time, where n and m are the sizes of A and B, respectively. You can improve this time to O(nlogn + mlogm), if n ~ m.
n log n + m log mtime.Find the intersection in
n+mtime: