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]}`);
});
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem