I was asked this on an interview this past week, and I didn’t have the answer (the correct answer anyways). Say for instance you have list A which has the following elements [1,3,5,7,9,10] and then you have list B, which has the following elements: [3,4,5,6,7], and you want to know which elements in list B are in list A. My answer was:
for item in listA:
for item1 in listB:
if item1 == item:
put item1 in some third list
But I know this is bad, because say listA is one million elements, and listB is a hundred thousand, this solution is just rubbish.
What’s the best way to achieve something like this without iteration of both lists?
I’d suggest converting them both to sets and doing an intersection:
Edit: Note that this will remove any duplicate elements that were in both lists. So if we had
listA = [1,1,2,2,3]andlistB = [1,1,2,3]then the intersection will only beset([1,2,3]). Also, for a worst-case estimate, this will be as slow as the list comprehension –O(n * m), where n and m are the respective lengths of the lists. Average case is a far betterO(n) + O(m) + O(min(m,n)) == O(max(m,n)), however.