3 Sum – All Distinct Triplets with given Sum in an Array
Last Updated :
08 Jan, 2025
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.
C++
// C++ program to find all the distinct triplets having sum
// equal to given target by exploring all the triplets
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int>> threeSum(vector<int>& arr, int target) {
vector<vector<int>> res;
int n = arr.size();
// Generating all possible triplets
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
if (arr[i] + arr[j] + arr[k] == target) {
vector<int> curr = {arr[i], arr[j], arr[k]};
sort(curr.begin(), curr.end());
// If triplet doesn't exist in the res, then only insert it.
if (find(res.begin(), res.end(), curr) == res.end())
res.push_back(curr);
}
}
}
}
return res;
}
int main() {
vector<int> arr = {12, 3, 6, 1, 6, 9};
int target = 24;
vector<vector<int>> ans = threeSum(arr, target);
for(vector<int> triplet : ans)
cout << triplet[0] << " " << triplet[1] << " " << triplet[2] << endl;
return 0;
}
C
// C program to find all the distinct triplets having sum
// equal to given target by exploring all the triplets
#include <stdio.h>
#include <stdlib.h>
int compare(const void* a, const void* b) {
return (*(int*)a - *(int*)b);
}
// Function to check whether this triplet already exist in res
int findTriplet(int res[][3], int* resSize, int triplet[]) {
for (int i = 0; i < *resSize; i++) {
if (res[i][0] == triplet[0] && res[i][1] == triplet[1] && res[i][2] == triplet[2]) {
return 1;
}
}
return 0;
}
void threeSum(int arr[], int n, int target, int res[][3], int* resSize) {
// Generating all possible triplets
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
if (arr[i] + arr[j] + arr[k] == target) {
int curr[3] = {arr[i], arr[j], arr[k]};
qsort(curr, 3, sizeof(int), compare);
// If triplet doesn't exist in the res, then only insert it
if (!findTriplet(res, &resSize, curr)) {
res[*resSize][0] = curr[0];
res[*resSize][1] = curr[1];
res[*resSize][2] = curr[2];
(*resSize)++;
}
}
}
}
}
}
int main() {
int arr[] = {12, 3, 6, 1, 6, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 24;
int res[100][3];
int resSize = 0;
threeSum(arr, n, target, res, &resSize);
for (int i = 0; i < resSize; i++)
printf("%d %d %d\n", res[i][0], res[i][1], res[i][2]);
return 0;
}
Java
// Java program to find all the distinct triplets having sum
// equal to given target by exploring all the triplets
import java.util.*;
class GfG {
public static List<List<Integer>> threeSum(int[] arr, int target) {
List<List<Integer>> res = new ArrayList<>();
int n = arr.length;
// Generating all possible triplets
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
if (arr[i] + arr[j] + arr[k] == target) {
List<Integer> curr = Arrays.asList(arr[i], arr[j], arr[k]);
Collections.sort(curr);
// If triplet doesn't exist in the res, then only insert it.
if (!res.contains(curr)) {
res.add(curr);
}
}
}
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {12, 3, 6, 1, 6, 9};
int target = 24;
List<List<Integer>> ans = threeSum(arr, target);
for (List<Integer> triplet : ans) {
System.out.println(triplet.get(0) + " " + triplet.get(1) + " " + triplet.get(2));
}
}
}
Python
# Python program to find all the distinct triplets having sum
# equal to given target by exploring all the triplets
def threeSum(arr, target):
res = []
n = len(arr)
# Generating all possible triplets
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
if arr[i] + arr[j] + arr[k] == target:
curr = sorted([arr[i], arr[j], arr[k]])
# If triplet doesn't exist in the res, then only insert it.
if curr not in res:
res.append(curr)
return res
if __name__ == "__main__":
arr = [12, 3, 6, 1, 6, 9]
target = 24
ans = threeSum(arr, target)
for triplet in ans:
print(triplet[0], triplet[1], triplet[2])
C#
// C# program to find all the distinct triplets having sum
// equal to given target by exploring all the triplets
using System;
using System.Collections.Generic;
using System.Linq;
class GfG {
static List<List<int>> ThreeSum(int[] arr, int target) {
List<List<int>> res = new List<List<int>>();
int n = arr.Length;
// Generating all possible triplets
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
if (arr[i] + arr[j] + arr[k] == target) {
List<int> curr = new List<int> { arr[i], arr[j], arr[k] };
curr.Sort();
// If triplet doesn't exist in the res, then only insert it.
if (!res.Any(x => x.SequenceEqual(curr))) {
res.Add(curr);
}
}
}
}
}
return res;
}
static void Main() {
int[] arr = { 12, 3, 6, 1, 6, 9 };
int target = 24;
List<List<int>> ans = ThreeSum(arr, target);
foreach (var triplet in ans) {
Console.WriteLine(triplet[0] + " " + triplet[1] + " " + triplet[2]);
}
}
}
JavaScript
// JavaScript program to find all the distinct triplets having sum
// equal to given target by exploring all the triplets
function threeSum(arr, target) {
const res = [];
const n = arr.length;
// Generating all possible triplets
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
for (let k = j + 1; k < n; k++) {
if (arr[i] + arr[j] + arr[k] === target) {
const curr = [arr[i], arr[j], arr[k]].sort((a, b) => a - b);
// If triplet doesn't exist in the res, then only insert it.
if (!res.some(triplet => JSON.stringify(triplet) === JSON.stringify(curr))) {
res.push(curr);
}
}
}
}
}
return res;
}
const arr = [12, 3, 6, 1, 6, 9];
const target = 24;
const ans = threeSum(arr, target);
ans.forEach(triplet => console.log(triplet.join(' ')));
[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.
C++
// C++ program to find all unique triplets having sum
// equal to target using hashing
#include<bits/stdc++.h>
using namespace std;
vector<vector<int>> threeSum(vector<int>& arr, int target) {
int n = arr.size();
// Ideally we should us an unordered_set here, but C++
// does not support vector as a key in an unordered_set
// So we have used set to keep the code simple. However
// set internally uses Red Black Tree and has O(Log n)
// time complexities for operations
set<vector<int>> resSet;
// Generating all pairs
for (int i = 0; i < n; i++) {
unordered_set<int> s;
for(int j = i + 1; j < n; j++) {
int complement = target - arr[i] - arr[j];
// If the complement exist in the hash set then we
// have found the triplet with sum, target
if(s.find(complement) != s.end()) {
vector<int> curr = {arr[i], arr[j], complement};
sort(curr.begin(), curr.end());
resSet.insert(curr);
}
s.insert(arr[j]);
}
}
return vector<vector<int>>(resSet.begin(), resSet.end());
}
int main() {
vector<int> arr = {12, 3, 6, 1, 6, 9};
int target = 24;
vector<vector<int>> ans = threeSum(arr, target);
for(vector<int> triplet : ans)
cout << triplet[0] << " " << triplet[1] << " " << triplet[2] << endl;
return 0;
}
Java
// Java program to find all unique triplets having sum
// equal to target using hashing
import java.util.*;
class GfG {
static List<List<Integer>> threeSum(int[] arr, int target) {
int n = arr.length;
// Set to handle duplicates
Set<List<Integer>> resSet = new HashSet<>();
// Generating all pairs
for (int i = 0; i < n; i++) {
Set<Integer> s = new HashSet<>();
for (int j = i + 1; j < n; j++) {
int complement = target - arr[i] - arr[j];
// If the complement exists in the hash set then we
// have found the triplet with sum, target
if (s.contains(complement)) {
List<Integer> curr = Arrays.asList(arr[i], arr[j], complement);
Collections.sort(curr);
resSet.add(curr);
}
s.add(arr[j]);
}
}
return new ArrayList<>(resSet);
}
public static void main(String[] args) {
int[] arr = {12, 3, 6, 1, 6, 9};
int target = 24;
List<List<Integer>> ans = threeSum(arr, target);
for (List<Integer> triplet : ans) {
System.out.println(triplet.get(0) + " " + triplet.get(1) + " " + triplet.get(2));
}
}
}
Python
# Python program to find all unique triplets having sum
# equal to target using hashing
def threeSum(arr, target):
n = len(arr)
# Set to handle duplicates
resSet = set()
# Generating all pairs
for i in range(n):
s = set()
for j in range(i + 1, n):
complement = target - arr[i] - arr[j]
# If the complement exists in the hash set then we
# have found the triplet with sum, target
if complement in s:
curr = tuple(sorted([arr[i], arr[j], complement]))
resSet.add(curr)
s.add(arr[j])
return list(resSet)
if __name__ == "__main__":
arr = [12, 3, 6, 1, 6, 9]
target = 24
ans = threeSum(arr, target)
for triplet in ans:
print(triplet[0], triplet[1], triplet[2])
C#
// C# program to find all unique triplets having sum
// equal to target using hashing
using System;
using System.Collections.Generic;
class GfG {
static List<List<int>> ThreeSum(int[] arr, int target) {
int n = arr.Length;
// Set to handle duplicates
HashSet<List<int>> resSet = new HashSet<List<int>>(new ListComparer());
// Generating all pairs
for (int i = 0; i < n; i++) {
HashSet<int> s = new HashSet<int>();
for (int j = i + 1; j < n; j++) {
int complement = target - arr[i] - arr[j];
// If the complement exists in the hash set then we
// have found the triplet with sum, target
if (s.Contains(complement)) {
List<int> curr = new List<int> { arr[i], arr[j], complement };
curr.Sort();
resSet.Add(curr);
}
s.Add(arr[j]);
}
}
return new List<List<int>>(resSet);
}
static void Main() {
int[] arr = { 12, 3, 6, 1, 6, 9 };
int target = 24;
List<List<int>> ans = ThreeSum(arr, target);
foreach (var triplet in ans) {
Console.WriteLine($"{triplet[0]} {triplet[1]} {triplet[2]}");
}
}
class ListComparer : IEqualityComparer<List<int>> {
public bool Equals(List<int> x, List<int> y) {
if (x.Count != y.Count) return false;
for (int i = 0; i < x.Count; i++) {
if (x[i] != y[i]) return false;
}
return true;
}
public int GetHashCode(List<int> obj) {
int hash = 17;
foreach (int i in obj) {
hash = hash * 31 + i.GetHashCode();
}
return hash;
}
}
}
JavaScript
// JavaScript program to find all unique triplets having sum
// equal to target using hashing
function threeSum(arr, target) {
const n = arr.length;
// Set to handle duplicates
const resSet = new Set();
// Generating all pairs
for (let i = 0; i < n; i++) {
const s = new Set();
for (let j = i + 1; j < n; j++) {
const complement = target - arr[i] - arr[j];
// If the complement exists in the hash set then we
// have found the triplet with sum, target
if (s.has(complement)) {
const curr = [arr[i], arr[j], complement];
curr.sort((a, b) => a - b);
resSet.add(curr.toString());
}
s.add(arr[j]);
}
}
return Array.from(resSet).map(triplet => triplet.split(',').map(Number));
}
const arr = [12, 3, 6, 1, 6, 9];
const target = 24;
const ans = threeSum(arr, target);
for (const triplet of ans) {
console.log(triplet[0], triplet[1], triplet[2]);
}
[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.
C++
// C++ program to find all the distinct triplets having sum
// equal to given target using two pointer technique
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int>> threeSum(vector<int>& arr, int target) {
vector<vector<int>> res;
int n = arr.size();
sort(arr.begin(), arr.end());
for (int i = 0; i < n; i++) {
// Skip duplicates for i
if (i > 0 && arr[i] == arr[i - 1]) continue;
// Two pointer technique
int j = i + 1, k = n - 1;
while(j < k) {
int sum = arr[i] + arr[j] + arr[k];
if(sum == target) {
vector<int> curr = {arr[i], arr[j], arr[k]};
res.push_back(curr);
j++;
k--;
// Skip duplicates for j and k
while(j < n && arr[j] == arr[j - 1]) j++;
while(k > j && arr[k] == arr[k + 1]) k--;
}
else if(sum < target) {
j++;
}
else {
k--;
}
}
}
return res;
}
int main() {
vector<int> arr = {12, 3, 6, 1, 6, 9};
int target = 24;
vector<vector<int>> ans = threeSum(arr, target);
for(vector<int> triplet : ans)
cout << triplet[0] << " " << triplet[1] << " " << triplet[2] << endl;
return 0;
}
Java
// Java program to find all the distinct triplets having sum
// equal to target using two pointer technique
import java.util.*;
class GfG {
static List<List<Integer>> threeSum(int[] arr, int target) {
List<List<Integer>> res = new ArrayList<>();
int n = arr.length;
Arrays.sort(arr);
for (int i = 0; i < n; i++) {
// Skip duplicates for i
if (i > 0 && arr[i] == arr[i - 1]) continue;
// Two pointer technique
int j = i + 1, k = n - 1;
while (j < k) {
int sum = arr[i] + arr[j] + arr[k];
if (sum == target) {
List<Integer> curr = Arrays.asList(arr[i], arr[j], arr[k]);
res.add(curr);
j++;
k--;
// Skip duplicates for j and k
while (j < n && arr[j] == arr[j - 1]) j++;
while (k > j && arr[k] == arr[k + 1]) k--;
}
else if (sum < target) {
j++;
}
else {
k--;
}
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {12, 3, 6, 1, 6, 9};
int target = 24;
List<List<Integer>> ans = threeSum(arr, target);
for (List<Integer> triplet : ans) {
System.out.println(triplet.get(0) + " " + triplet.get(1) + " " + triplet.get(2));
}
}
}
Python
# Python program to find all the distinct triplets having sum
# equal to target using two pointer technique
def three_sum(arr, target):
res = []
n = len(arr)
arr.sort()
for i in range(n):
# Skip duplicates for i
if i > 0 and arr[i] == arr[i - 1]:
continue
# Two pointer technique
j, k = i + 1, n - 1
while j < k:
sum_value = arr[i] + arr[j] + arr[k]
if sum_value == target:
res.append([arr[i], arr[j], arr[k]])
j += 1
k -= 1
# Skip duplicates for j and k
while j < n and arr[j] == arr[j - 1]:
j += 1
while k > j and arr[k] == arr[k + 1]:
k -= 1
elif sum_value < target:
j += 1
else:
k -= 1
return res
arr = [12, 3, 6, 1, 6, 9]
target = 24
ans = three_sum(arr, target)
for triplet in ans:
print(f"{triplet[0]} {triplet[1]} {triplet[2]}")
C#
// C# program to find all the distinct triplets having sum
// equal to target using two pointer technique
using System;
using System.Collections.Generic;
class GfG {
static List<List<int>> ThreeSum(int[] arr, int target) {
List<List<int>> res = new List<List<int>>();
int n = arr.Length;
Array.Sort(arr);
for (int i = 0; i < n; i++) {
// Skip duplicates for i
if (i > 0 && arr[i] == arr[i - 1]) continue;
// Two pointer technique
int j = i + 1, k = n - 1;
while (j < k) {
int sum = arr[i] + arr[j] + arr[k];
if (sum == target) {
List<int> curr = new List<int> { arr[i], arr[j], arr[k] };
res.Add(curr);
j++;
k--;
// Skip duplicates for j and k
while (j < n && arr[j] == arr[j - 1]) j++;
while (k > j && arr[k] == arr[k + 1]) k--;
}
else if (sum < target) {
j++;
}
else {
k--;
}
}
}
return res;
}
static void Main() {
int[] arr = { 12, 3, 6, 1, 6, 9 };
int target = 24;
List<List<int>> ans = ThreeSum(arr, target);
foreach (var triplet in ans) {
Console.WriteLine($"{triplet[0]} {triplet[1]} {triplet[2]}");
}
}
}
JavaScript
// JavaScript program to find all the distinct triplets having sum
// equal to target using two pointer technique
function threeSum(arr, target) {
let res = [];
let n = arr.length;
arr.sort((a, b) => a - b);
for (let i = 0; i < n; i++) {
// Skip duplicates for i
if (i > 0 && arr[i] === arr[i - 1]) continue;
// Two pointer technique
let j = i + 1, k = n - 1;
while (j < k) {
let sum = arr[i] + arr[j] + arr[k];
if (sum === target) {
res.push([arr[i], arr[j], arr[k]]);
j++;
k--;
// Skip duplicates for j and k
while (j < n && arr[j] === arr[j - 1]) j++;
while (k > j && arr[k] === arr[k + 1]) k--;
}
else if (sum < target) {
j++;
}
else {
k--;
}
}
}
return res;
}
const arr = [12, 3, 6, 1, 6, 9];
const target = 24;
const ans = threeSum(arr, target);
ans.forEach(triplet => {
console.log(`${triplet[0]} ${triplet[1]} ${triplet[2]}`);
});
Explore
DSA Fundamentals
Data Structures
Algorithms
Advanced
Interview Preparation
Practice Problem