VOOZH about

URL: https://www.geeksforgeeks.org/dsa/unique-triplets-sum-given-value/

⇱ 3 Sum – All Distinct Triplets with given Sum in an Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

3 Sum – All Distinct Triplets with given Sum in an Array

Last Updated : 28 Jan, 2026

Given an array arr[], and an integer target, find all possible unique triplets in the array whose sum is equal to the given target value. We can return triplets in any order, but all the returned triplets should be internally sorted, i.e., for any triplet [q1, q2, q3], the condition q1 ≤ q2 ≤ q3 should hold.

Examples:

Input: arr[] = [12, 3, 6, 1, 6, 9], target = 24
Output: [[3, 9, 12], [6, 6, 12]]
Explanation: There are two unique triplets that add up to 24:
3 + 9 + 12 = 24
6 + 6 + 12 = 24

Input: arr[] = [-2, 0, 1, 1, 2], target = 10
Output: []
Explanation: There is not triplet with sum 10.

[Naive Approach] - By Exploring all the triplets - O(n^4) Time and O(1) Space

We use three nested loops to generate all possible triplets, then check if their sum is equal to the target. If it is, we run an additional loop to check if the triplet is already in the result; if not, we add it.


Output
3 9 12
6 6 12

[Better Approach] - Using Hashing - O(n^2 log n) Time and O(n) Space

The idea is to maintain a hash set to track whether a particular element occurred in the array so far or not. As we traverse all pairs using two nested loops, for each pair {arr[i], arr[j]}, we check if the complement (target - arr[i] - arr[j]) is already in the set. If it is, we have found a triplet whose sum equals the target. Each valid triplet is inserted into ta hash set to avoid duplicates.


Output
3 9 12
6 6 12

[Expected Approach] - Using Two Pointers Technique - O(n^2) Time and O(1) Space

The idea is to sort the array and use two pointers technique to find all the triplets. We will traverse the array and fix the first element of the triplet then, Initialize two pointers at the beginning and end of the remaining array. Now, compare the sum of elements at these pointers:

  • If sum = target, store the triplet and skip duplicates to ensure they are distinct.
  • If sum < target, we move the left pointer towards right.
  • If sum > target, we move the right pointer towards left.

Output
3 9 12
6 6 12
Comment
Article Tags:
Article Tags: