Reputation: 395
Suppose we have two lists of lengths n and m respectively:
val l1 = Seq(1,2,3,4,5,6,7,8,9,0)
val l2 = Seq(2,4,6,8,10,12)
Is there a way to calculate their intersection wiht less than O(n·m)?
That is
val result = Seq(2,4,6,8)
EDIT: we can assume our lists are sorted.
Upvotes: 0
Views: 117
Reputation: 2307
Put one of the items into a hash set. O(min(n,m))
var set2 = new HashSet<int>(){2,4,6,8,10,12};
Take the other set and check if it exists in hash set. Each access is O(1) since we need the other set and we created the hash set with the shorter set that means the time is O(max(m,n)) if it return true in the other set add it to your results.
Upvotes: 2
Reputation: 6974
For sorted lists the following Algorithm should work:
You can have 2 pointers say (i and j) one at l1 another at l2.
Now you can iterate on l1 and l2 such that
while (i< l1.size && j < l2.size ) {
if l1[i] < l2[j]
i++
else if (l1[i] == l2[j] )
i++; j++; output = output U {l1[i]}
else
j++
}
This should be in O(max(m,n))
Upvotes: 2