# Optimizing solution of Sum of Pairs: Codewars in Python

I need help to optimize my code for huge lists with approx. 10000000 elements. Is there a way to improve my algorithm or should I try to build a new one using a completely different approach? Task: given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum.

def sum_pairs(ints, s):
lst1 = []
for n in ints:
if n in lst1:
return [s-n, n]
lst1.append(s-n)

lst3 = list(range(1,10000000))

sum_pairs(lst3, 20000000)

*Times out :(

#Using set() every time we add new item to the list doesn't help

def sum_pairs(ints, s):
lst1 = []
for n in ints:
lst2 = set(lst1)
if n in lst2:
return[s-n, n]
lst1.append(s-n)

• What is the purpose of the code? Commented Jan 20, 2021 at 18:07
• Btw you should tag this as python Commented Jan 20, 2021 at 19:22
• I mean that you should just completely take the lst1 list out of the program and use a set instead. Commented Jan 20, 2021 at 19:29
• Please replace the top image with a code block containing equivalent text. Commented Jan 20, 2021 at 20:17

You could use a set as lst1 instead of a list. Every time you check if n is in lst1, it’s $$\ O(n) \$$ time complexity. Using a set instead will lower that to $$\ O(1) \$$.