Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an efficient way to find disjoint elements in two arrays?

Tags:

arrays

ruby

I have the following arrays:

A = [1,2,3,4,5]
B = [2,6,7,1]

I want to find the disjoint elements, which are as follows:

output = [3,4,5,6,7]

I was able to achieve this as follows,

output = A + B - (A & B)

but it is inefficient, as I'm adding two arrays and then removing common elements. It is similar to finding non-intersecting elements. Can I do it better than this? If so, how?

like image 670
Abhishek Avatar asked Feb 19 '16 10:02

Abhishek


1 Answers

How about just selecting elements in A not in B and elements in B not in A.

(A - B) + (B - A)
like image 168
SteveTurczyn Avatar answered Sep 23 '22 17:09

SteveTurczyn