A very simple solution that really executes O (N) times using array references. If you want to list all the output pairs, then of course (as notes), in the worst case, he should take O (N ^ 2).
from collections import defaultdict def findpairs(arr, target): flip = defaultdict(list) for i, j in enumerate(arr): flip[j].append(i) for i, j in enumerate(arr): if target-j in flip: yield i, flip[target-j]
Post-processing to get all output values (and filter responses (i,i) ):
def allpairs(arr, target): for i, js in findpairs(arr, target): for j in js: if i < j: yield (i, j)
source share