The missing de meets the Big O
March 27, 2007 1:59 PM
Subscribe
Given two unsorted lists, size N and M (N < M), how long [ O (???) ] and how much storage [ O (???) ] would be required to find elements in common between N and M (the number of common elements could range from 0 to N)? How would you go about doing this?
Is there anything that could be done to improve this time by restructuring the data (i.e. sorted list or something else entirely) and what benefit would this have on the time and storage needed?
Note: This question was inspired by the MeTa meetups sidebar, which says there is an April 12 meetup in "Berlin, DE" which to me could be interpreted as either Delaware or Germany. Fortunately, there is no Berlin in Delaware, but I was curious about how to go about finding such collisions if we had full lists of all towns/cities in 2 places and determining where colliding meetups might be possible.
posted by langeNU to computers & internet (29 comments total)
1 user marked this as a favorite
In more detail:
Let A and B be the two sorted lists. For convenience, let them be represented as arrays A[1..N] and B[1..M].
1. Let p = 1 and q = 1 2. If A[p] < B[q] then p = p+1 Else if A[p] > B[q] then q = q+1 Else if A[p] == B[q] then Output A[p] p = p+1 q = q+1 3. If p>N or q>M then Exit Else Goto 2.The time and space of this method is dominated by the sorting step.posted by mhum at 2:23 PM on March 27, 2007