
Asked in BrowserStack
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.
Be the first one to answer
Add answer anonymously...
Interview Questions Asked to Software Developer Intern at Other Companies
Top Skill-Based Questions for BrowserStack Software Developer Intern
Algorithms Interview Questions and Answers
250 Questions
Data Structures Interview Questions and Answers
250 Questions
Web Development Interview Questions and Answers
250 Questions
Operating Systems Interview Questions and Answers
250 Questions
System Design Interview Questions and Answers
250 Questions
C++ Interview Questions and Answers
150 Questions
Stay ahead in your career. Get AmbitionBox app


Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+
Reviews
10L+
Interviews
4 Cr+
Salaries
1.5 Cr+
Users
Contribute to help millions
AmbitionBox Awards
Get AmbitionBox app

