Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to find if two sets intersect

Let's say I have two arrays:

int ArrayA[] = {5, 17, 150, 230, 285};

int ArrayB[] = {7, 11, 57, 110, 230, 250};

Both arrays are sorted and can be any size. I am looking for an efficient algorithm to find if the arrays contain any duplicated elements between them. I just want a true/false answer, I don't care which element is shared or how many.

The naive solution is to loop through each item in ArrayA, and do a binary search for it in ArrayB. I believe this complexity is O(m * log n).

Because both arrays are sorted, it seems like there should be a more efficient algorithm.

I would also like a generic solution that doesn't assume that the arrays hold numbers (i.e. the solution should also work for strings). However, the comparison operators are well defined and both arrays are sorted from least to greatest.

like image 380
Imbue Avatar asked Oct 29 '08 01:10

Imbue


People also ask

How do you find the intersection of two sets?

The intersection of two or more given sets is the set of elements that are common to each of the given sets. The intersection of sets is denoted by the symbol '∩'. In the case of independent events, we generally use the multiplication rule, P(A ∩ B) = P( A )P( B ).

How do you know if two sets are disjoint?

Two sets are disjoint set when they have no common elements. In other words, if we get the intersection of two sets, then we will get null set. The method is simple, in this algorithm, two sets are given.

How do you find intersections in C++?

C++ Algorithm set_intersection() function is used to find the intersection of two sorted ranges[first1, last1) and [first2, last2), which is formed only by the elements that are present in both sets.

What checks whether the two given sets are equal?

Two arrays are said to be equal if both of them contain the same set of elements, the permutation of the elements may be different though. If there are repetitions, then counts of repeated elements must also be the same for two arrays to be equal.


1 Answers

Pretend that you are doing a mergesort, but don't send the results anywhere. If you get to the end of either source, there is no intersection. Each time you compare the next element of each, if they are equal, there is an intersection.

For example:

counterA = 0;
counterB = 0;
for(;;) {
    if(counterA == ArrayA.length || counterB == ArrayB.length)
        return false;
    else if(ArrayA[counterA] == ArrayB[counterB])
        return true;
    else if(ArrayA[counterA] < ArrayB[counterB])
        counterA++;
    else if(ArrayA[counterA] > ArrayB[counterB])
        counterB++;
    else
        halt_and_catch_fire();
}
like image 89
Andru Luvisi Avatar answered Oct 04 '22 04:10

Andru Luvisi