Created
November 9, 2016 18:21
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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