Skip to content

Instantly share code, notes, and snippets.

@vetional
Created October 9, 2017 03:22
Show Gist options
  • Save vetional/ae0d1a3f4396ef2cd5563388a903c6e0 to your computer and use it in GitHub Desktop.
Save vetional/ae0d1a3f4396ef2cd5563388a903c6e0 to your computer and use it in GitHub Desktop.
3sum problem created by vetional - https://repl.it/MS4f/0
# Determine if any 3 integers in an array sum to 0.
# For example, for array [4, 3, -1, 2, -2, 10], the function should return true since 3 + (-1) + (-2) = 0. To make things simple, each number can be used at most once.
def solution(A):
A.sort() # O(nlogn)
print A
for i, x in enumerate(A): # O(n**2)
start = 0
end = len(A) - 1
while start < end:
# make sure the start or end
# is not the currrent number
if start == i:
start += 1
if end == i:
end -= 1
s = A[start] + A[end]
print start, end, s, -1 * x
if s == -1 * x:
print "found: ", A[start] , A[end], x
return True
if s > -1 * x:
end -= 1
elif s < -1 * x:
start += 1
return False
A = [4, 3, -1, 2, -2, 10]
print solution(A)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment