Find Triplets with Given Sum Problem Statement

Given an array ARR consisting of N integers, your task is to identify all distinct triplets within the array that sum up to a given integer K.

Explanation:

An array contains a triplet {ARR[i], ARR[j], ARR[k]} summing to K if there exist three indices i, j, and k such that i != j, j != k, and i != k, while satisfying ARR[i] + ARR[j] + ARR[k] = K.

Input:

T  # Number of test cases
N # Size of the array
ARR # Array elements (space-separated integers)
K # Target sum for the triplets

Output:

For each test case, print each valid triplet on a new line or return an empty list if no such triplet exists, which will be indicated by "-1" in the output.

Example:

Input:
2
5
1 2 3 4 5
9
6
-1 0 1 2 -1 -4
0
Output:
2 3 4
-1 0 1
-1 2 -1

Constraints:

  • 1 <= T <= 50
  • 1 <= N <= 103
  • -106 <= ARR[i] <= 106
  • -109 <= K <= 109
  • Time Limit: 1 second
Note:
You are not required to print anything; the output mechanism is handled for you. Just implement the function to process the input and determine triplets.
AnswerBot
4mo

The task is to find all distinct triplets in an array that sum up to a given integer.

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

  • Use a set to store unique triplets an...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Interview Questions Asked at Directi

Q. Stock Buy and Sell Problem Statement Given an array/list 'prices' where the elem...read more
Q. Box Stacking Problem Statement Consider you are provided with 'n' different type...read more
Q. Duplicate Elements in Array You are provided with an array or list called ARR, c...read more
Software Developer 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