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

algorithm, c, c++, java

Solution

Since this looks to me like a string algorithm, I'll assume for a moment that its not possible to sort this sequence (hence string) then you can use Longest Common Sequence algorithm (LCS)

Assuming the input size is constant, then the problem has a complexity of O(nxm), (length of the two inputs)

Problem

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?

Original source

Related problems