I don't think this is possible in o(n²) (i.e. better than n² ), but it can be done in o(n²) (i.e. as n² ) as follows:
First of all, the reverse list B to get B' (takes O(n) time), a list whose elements are sorted in descending order. First, consider the problem of finding two elements in lists A and B' that are summed with any given number:
We can do this as follows (Python code):
def getIndicesFromTwoArrays(A,B,t): a,b=0,0 while(A[a]+B[b]!=t): b=b+1 if b==len(B): return (-1,-1) if A[a]+B[b]<t: a=a+1 b=b-1 if a==len(A): return (-1,-1) return (a,b)
The uptime is O(n) . Extra O(1) space is required since we need to save only two pointers. Note that the above can easily be converted in such a way that it works with doubly linked lists.
Then, in general, we just have to do the following:
def test(A,B,C): B.reverse() for c in C: if getIndicesFromTwoArrays(A, B, c) != (-1,-1): return True return False
This leads to runtime o(n²) and additional space O(1) .
phimuemue
source share