Triplets with Given Sum Problem
Given an array or list ARR
consisting of N
integers, your task is to identify all distinct triplets within the array that sum up to a specified number K
.
Explanation:
A triplet is a set {ARR[i]
, ARR[j]
, ARR[k]
} such that the indices i
, j
, and k
are distinct (i.e., i != j
, j != k
, and i != k
) and their values add up to the target sum K
.
Input:
The first line of the input contains an integer T, representing the number of test cases.
The first line of each test case contains the integer N, representing the size of the array.
The second line of each test case contains N space-separated integers representing the elements of the array.
The third line of each test case contains the integer K, representing the target sum for the triplets.
Output:
For each test case, print every valid triplet in a separate line as three space-separated integers. If no such triplet exists, return an empty list and print "-1" instead.
Example:
Input:
2
5
1 2 3 4 5
9
4
1 1 1 2
5
Output:
1 3 5
1 1 1
-1
Explanation:
In the first test case, the triplet {1, 3, 5} adds up to 9. In the second test case, no such triplet exists, hence "-1" is printed.
Constraints:
1 ≤ T ≤ 50
1 ≤ N ≤ 103
-106 ≤ ARR[i] ≤ 106
-109 ≤ K ≤ 109
Note: You don't need to execute any print operations, as they are handled separately. Implement the functionality as described.
The task is to find all distinct triplets in an array that add up to a given sum.
Iterate through the array and fix the first element of the triplet.
Use two pointers approach to find the other two elem...read more
Top Myntra Mern Stack Developer interview questions & answers
Popular interview questions of Mern Stack Developer
Reviews
Interviews
Salaries
Users/Month