Skip to content

Instantly share code, notes, and snippets.

@samidarko
Last active March 8, 2018 06:37
Show Gist options
  • Save samidarko/3c67bbbdf3400022c82981ceca470624 to your computer and use it in GitHub Desktop.
Save samidarko/3c67bbbdf3400022c82981ceca470624 to your computer and use it in GitHub Desktop.
Find if sum a of pair of integer exists in an array
def brute_force(arr, s):
for i in arr:
for j in arr:
if i + j == s:
print("{} + {} = {}".format(i, j, s))
# brute_force([5, 3, 7, 0, 1, 4, 2], 5)
def binary_search(arr, s):
left = 0
right = len(arr) - 1
while True:
if left > right:
return None
m = (left + right) // 2
e = arr[m]
if e < s:
left = m + 1
elif e > s:
right = m - 1
else:
return m
def n_log_n(arr, s):
for e in arr:
i = binary_search(arr, s - e)
if i is not None:
print("{} + {} = {}".format(i, e, s))
# n_log_n([0, 1, 2, 3, 4, 5, 7], 5)
def n(arr, s):
d = {}
for e in arr:
d[e] = e
for i, e in enumerate(arr):
t = s - e
if t in d and d[t] != i:
print("{} + {} = {}".format(d[t], e, s))
n([5, 3, 7, 0, 1, 4, 2], 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment