Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the intersection between two arrays as a new array?

I faced this problem many times during various situations. It is generic to all programming languages although I am comfortable with C or Java.

Let us consider two arrays (or collections):

char[] A = {'a', 'b', 'c', 'd'}; char[] B = {'c', 'd', 'e', 'f'}; 

How do I get the common elements between the two arrays as a new array? In this case, the intersection of array A and B is char[] c = {'c', 'd'}.

I want to avoid the repeated iteration of one array inside the other array which will increase the execution time by (length of A times length of B) which is too much in the case of huge arrays.

Is there any way we could do a single pass in each array to get the common elements?

like image 323
Ranjan Sarma Avatar asked Nov 07 '12 13:11

Ranjan Sarma


People also ask

How do you find the intersection of two arrays?

Solution idea We run two nested loops: an outer loop from i = 0 to m - 1 to pick each element X[i] and an inner loop from j = 0 to n - 1 to search X[i] linearly in Y[]. Whenever we found an element common to both X[] and Y[] i.e. X[i] == Y[j], we add aby one of it to the output list intersection[].


1 Answers

foreach element e in array A     insert e into hash table H  foreach element e in array B     if H contains e          print e 

This algorithm is O(N) in time and O(N) in space.

To avoid the extra space, you can use the sorting based approach.

like image 184
codaddict Avatar answered Sep 25 '22 02:09

codaddict