# Count the triplets GeeksForGeeks

Given an array of distinct integers. The task is to count all the triplets such that sum of two elements equals the third element.

Input: The first line of input contains the number of test cases. Each test case consists of two lines.

First line of contains size of array
The second line contains N space separated elements.

Output: For each test case, print the count of all triplets, in new line Else print “-1”.

# SOLUTION BODY

``````def solution(array):

triplets  = 0
range_len = len(array)

for i in range(range_len):
temp_arr = array[i+1::]
val = set(array)

for j in temp_arr:
value = array[i] + j
if value in val:
triplets = triplets + 1
else:
pass
if triplets == 0:
return -1
else:
return triplets
``````

Things added: To check if triplet exists, I have used sets{} as it has O(1) lookup time..
Execution Time: 0.71

``````def inputList(n):

while True:
print(f"Enter space separated elements of size {n}")
array = [int(num) for num in input().split()]
if len(array) == n:
break
else:
print("Entered value doesn't match with size N provided")

array.sort()
return array
``````

## MAIN BODY

``````def main():
while True:
try:
T = int(input("Enter integer T denoting the number of test cases: "))
array = {}

for num in range(T):
N = int(input("Enter integer N denoting size of array: "))
array[num+1] = inputList(N)
print("")
triplet = solution(array[num+1])

print(f"Number of triplets in {array[num+1]} is {triplet}n")
break
except Exception as e:
print(e)
``````
``````main()
``````
``````Enter integer T denoting the number of test cases: 2
Enter integer N denoting size of array: 4
Enter space separated elements of size 4
1 5 3 2

Number of triplets in [1, 2, 3, 5] is 2

Enter integer N denoting size of array: 3
Enter space separated elements of size 3
3 2 7

Number of triplets in [2, 3, 7] is -1
``````

Scripting