Skip to content

Instantly share code, notes, and snippets.

@jatinsharrma
Last active May 15, 2020 18:40
Show Gist options
  • Save jatinsharrma/bf547060b0b11372b25cda118f701213 to your computer and use it in GitHub Desktop.
Save jatinsharrma/bf547060b0b11372b25cda118f701213 to your computer and use it in GitHub Desktop.
Find all triplets whose sum is equal to given number.
# ////////////////////////////////////////////////
# --------------Three Number Sum-----------------
# ///////////////////////////////////////////////
# time complexity O(n^2)
# space complexity O(n)
def tripletSum(arr, v):
l_n = len(arr)
result = []
for i in range(l_n): # runs n times
for j in range(i+1,l_n): # runs n-1 times
for k in range(j+1,l_n): # runs n-2 times
if arr[i] + arr[j] + arr[k] == v:
result.append([arr[i] , arr[j] , arr[k]])
return result
print(tripletSum([1,2,3,4,5,6,-1],6))
# time complexity O(n^2)
# space complexity O(n)
def tripletSum1(arr,v):
l_n = len(arr)
result = []
arr.sort()
for i in range(l_n): # runs n times
r = i+1
l = l_n-1
while l>r: # runs n-1 times
s_m = arr[i] + arr[r] + arr[l]
if s_m == v:
result.append([arr[i] , arr[l] , arr[r]])
r += 1
l -= 1
elif s_m < v:
r +=1
else:
l -= 1
return result
print(tripletSum([1,2,3,4,5,6,-1],6))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment