One of my friend was asked this question in an interview -
Put each element of the first array into a hash. For each item in the second array, if it's already in the hash, remove it, else add it. At the end you have a hash with two keys, which are your unique elements.
Simple verison in Ruby
def unique(a,b)
h={}
a.each do |ax|
h[ax]=true
end
b.each do |bx|
if h[bx]
h.delete(bx)
else
h[bx]=true
end
end
h.keys
end
With a little more Ruby personality, but still in the universe where we can't simply do (a | b) - (a & b)
or a.to_set ^ b.to_set
:
def unique(a,b)
h = {}
a.each do |ax|
h[ax] = true
end
b.each do |bx|
h.delete(bx) or h[bx] = true
end
h.keys
end