How to find the first common element in two arrays

algorithmsarraycomparisonsearch

How do you find the first common element in two arrays?

My attempt:

I looped through each at the same time and add the current value to a separate set for each of the lists. Also, check if the current element is already in the other list's set.

I have no idea if this works though and if so, why? I know it finds a common element but does it find the first common element? I can't think of counter examples but I'm having trouble convincing myself it's definitely correct. Also, even if it is correct, is there a better way of finding the first common element?

Best Answer

Sorting the arrays will not work. By changing the order you will not be able to determine which element matches first.

The intersect solution will also not work. To use it you'd have to copy both arrays to a set class, which by definition does not preserve order.

Your answer is correct. I would consider using hashsets to reduce search time.

Related Topic