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.

AnswerBot
4mo

Identify all distinct triplets within an array that sum up to a specified number.

  • Iterate through the array and use nested loops to find all possible triplets.

  • Use a set to store unique triplets and che...read more

Help your peers!
Select
Add answer anonymously...
BrowserStack Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
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

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits