Looks like Cheruvian beat me to it, but you can use a hash table to get O(n+m)
in average case:
*Insert all elements of m
into the table, taking (probably) constant time for each, assuming there aren't a lot with the same hash. This step is O(m)
*For each element of n
, check to see if it is in the table. If it is, return false. Otherwise, move on to the next. This takes O(n)
.
*If none are in the table, return true.
As I said before, this works because a hash table gives constant lookup time in average case. In the rare event that many unique elements in m
have the same hash, it will take slightly longer. However, most people don't need to care about hypothetical worst cases. For example, quick sort is used more than merge sort because it gives better average performance, despite the O(n^2)
upper bound.