Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to find intersection of two sets without using any data structure

I would like to know the algorithm to determine the intersection of two arrays of equal elements (say, integer) without using any external data structure (like hash table) efficiently (O(nlogn))?

like image 930
Neel Avatar asked Jul 15 '26 01:07

Neel


2 Answers

sort, then iterate using an iterator to each element array:

if A[iter1] > B[iter2]: increase iter2
else if A[iter1] < B[iter2]: increase iter1
else: element is in intersection, print and increase both iters

Sorting is O(nlogn), iterating is O(n), total O(nlogn)

like image 193
amit Avatar answered Jul 17 '26 16:07

amit


  • Sort the arrays
  • Loop through them and store matches

Something like...

var A = [0...N];
var B = [0...N];
var result = [];
Array.sort(A);
Array.Sort(B);
for(var x=0, y=0; x < N && y < N; x++) {
    while(A[x] < B[y] && y < N) {
        y++;
    }
    if(A[x] == B[y]) {
        result.push( B[y++] );
    }
}
like image 34
Louis Ricci Avatar answered Jul 17 '26 16:07

Louis Ricci