Triplet Sum
Given an array n integers, find and print all the unique triplets (a, b, c) in the array which give the sum K. (a+b+c=K).Input
The first line of the input will be space separated integers, denoting the elements of the array. The second line of the input will be an integer denoting the required sum KOutput
The output should be multiple lines, each line containing a unique triplet. The elements of the triple must be sorted in increasing order and all the triplets printed must be sorted in increasing order. Print "No Matching Triplets Found" if there are no triplets with the given sum.Explanation
Sample Input 1
0 12 17 8 9 21
29
Sample Output 1
(0, 8, 21)
(0, 12, 17)
(8, 9, 12)
Sample Input 2
0 1 2 3 5 7 13 17 19 19
22
Sample Output 2
(0, 3, 19)
(0, 5, 17)
(1, 2, 19)
(2, 3, 17)
(2, 7, 13)
The output should be printed exactly as shown in the above test cases.
# Program to find a triplet returns true if there is triplet
# with sum of a, b, c equal to 'K' present in arr[].
def TripletSum(arr, K):
arr_size = len(arr)
found=False
arr.sort()
for a in range(0, arr_size - 2):
b = a + 1
c = arr_size - 1
while (b < c):
if( arr[a] + arr[b] + arr[c] == K):
print(( arr[a], arr[b], arr[c]))
b+=1
c-=1
found = True
elif (arr[a] + arr[b] + arr[c] < K):
b += 1
else:
c -= 1
if (found == False):
print("No Matching Triplets Found")
# TEST
arr = [0, 1, 2, 3, 5, 7, 13, 17, 19, 19]
K = 22
TripletSum(arr, K)
# OUTPUT
(0, 3, 19)
(0, 5, 17)
(1, 2, 19)
(2, 3, 17)
(2, 7, 13)
Comments
Leave a comment