Skip to content

Instantly share code, notes, and snippets.

@tanmaybaranwal
Created April 21, 2021 09:24
Show Gist options
  • Save tanmaybaranwal/26e54a003422ad34987ff766fb91273d to your computer and use it in GitHub Desktop.
Save tanmaybaranwal/26e54a003422ad34987ff766fb91273d to your computer and use it in GitHub Desktop.
In how many ways can you find all the triplets in a given array of n distinct elements with a sum equal to 0?
def find_triplets(array):
n = len(array)
array.sort()
triplets = []
for index in range(0, n-1):
starting_pointer = index + 1
end_pointer = n - 1
curr_value = array[index]
while (starting_pointer < end_pointer):
if (curr_value + array[starting_pointer] + array[end_pointer] == 0):
temp_tuple = (curr_value, array[starting_pointer], array[end_pointer], )
triplets.append(temp_tuple)
starting_pointer = starting_pointer + 1
end_pointer = end_pointer - 1
found = True
elif (curr_value + array[starting_pointer] + array[end_pointer] < 0):
starting_pointer = starting_pointer + 1
else:
end_pointer = end_pointer - 1
if (not triplets):
print(" No Triplet Found")
return triplets
array = [1, -4, 5, -7, 2, 0, -1, -3]
find_triplets(array)
# Returns: [(-7, 2, 5), (-4, -1, 5), (-3, 1, 2), (-1, 0, 1)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment