Skip to content

Instantly share code, notes, and snippets.

@rupalbarman
Created April 30, 2017 02:52
Show Gist options
  • Select an option

  • Save rupalbarman/e9e48700b0d8c93d719c0ef2b07cc3ba to your computer and use it in GitHub Desktop.

Select an option

Save rupalbarman/e9e48700b0d8c93d719c0ef2b07cc3ba to your computer and use it in GitHub Desktop.
Three sum problem in python. Find three numbers from an array whose sum is x
'''
three sum, to find a+b+c== x in an array
'''
a= [-1,0,1,2,-1,-4] #the array/ list
x= 0 #the sum we need
s= set()
res= [] #holds groups of 3 numbers satisfying the condition
for i in range(len(a)-1):
ax= a[i]
l, r= i+1, len(a)-1
while l < r:
if x -(ax+ a[l]) in s:
res.append([ax, a[l], x -(ax+ a[l])])
else:
s.add(ax+ a[l])
l+=1
s.clear()
print(res) #[[-1, 2, -1], [0, -1, 1]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment