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...
Freshworks Senior Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

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

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter