Skip to content

Instantly share code, notes, and snippets.

@shreezan123
Created November 9, 2016 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shreezan123/c083b533afe482e8e264f755dee65b15 to your computer and use it in GitHub Desktop.
Save shreezan123/c083b533afe482e8e264f755dee65b15 to your computer and use it in GitHub Desktop.
Find pairs in an integer array whose sum is equal to input parameter (bonus: do it in linear time)
def sumnums(arr,sum):
anslist = []
dict = {}
for each in arr:
if each not in dict:
dict[each] = 1
else:
dict[each] += 1
print(dict)
for each in dict:
if dict[each] == 0:
break
target = sum - each
if target in dict:
anslist.append((each,target))
dict[each] -= 1
dict[target] -= 1
return anslist
print(sumnums([1,2,3,2,4,0],4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment