I have two sorted lists of integers. I would like to find all pairs of integers from the first and second list, respectively, that are within a certain distance of each other.
The naive approach is to check each pair, resulting in a O(N^2) time. I am sure there is a way to do it in O(N*logN) or maybe shorter.
In python, the naive O(N^2) approach is as follows:
def find_items_within(list1, list2, within):
for l1 in list1:
for l2 in list2:
if abs(l1 - l2) <= within:
yield (l1, l2)
Extra points for pythonic answers.
Application Note
I just wanted to point out the purpose of this little puzzle. I am searching a document and want to find all the occurrences of one term within a certain distance of another term. First you find the term vectors of both terms, then you can use the algorithms described below to figure out if they are within a given distance of each other.