Find a triplet such that sum of two equals to third element
Last Updated :
20 Feb, 2025
Given an array of integers, you have to find three numbers such that the sum of two elements equals the third element.
Examples:
Input: arr[] = [1, 2, 3, 4, 5]
Output: True
Explanation: The pair (1, 2) sums to 3.
Input: arr[] = [3, 4, 5]
Output: True
Explanation: No triplets satisfy the condition.
Input: arr[] = [2, 7, 9, 15]
Output: True
Explanation: The pair (2, 7) sums to 9.
[Naive Approach] Triple Loop Triplet Finder - O(n^3) time and O(1) space
This approach uses three nested loops to examine all possible triplets in the array. It checks if the sum of any two elements equals the third element and prints all such valid triplets.
C++
#include <bits/stdc++.h>
using namespace std;
bool findTriplet(vector<int>& arr) {
int n = arr.size();
// Iterate through all possible triplets
for (int i = 0; i < n - 2; i++) {
for (int j = i + 1; j < n - 1; j++) {
for (int k = j + 1; k < n; k++) {
// Check if sum of two elements equals the third element
if (arr[i] + arr[j] == arr[k] || arr[i] + arr[k] == arr[j] || arr[j] + arr[k] == arr[i]) {
return true;
}
}
}
}
return false;
}
// Driver Code with Predefined Input
int main() {
vector<int> arr = {1, 2, 3, 4, 5};
if (findTriplet(arr))
cout << "true" << endl;
else
cout << "false" << endl;
return 0;
}
C
#include <stdio.h>
#include <stdbool.h>
bool findTriplet(int arr[], int n) {
// Iterate through all possible triplets
for (int i = 0; i < n - 2; i++) {
for (int j = i + 1; j < n - 1; j++) {
for (int k = j + 1; k < n; k++) {
// Check if sum of two elements equals the third element
if (arr[i] + arr[j] == arr[k] || arr[i] + arr[k] == arr[j] || arr[j] + arr[k] == arr[i]) {
return true;
}
}
}
}
return false;
}
// Driver Code with Predefined Input
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
if (findTriplet(arr, n))
printf("true\n");
else
printf("false\n");
return 0;
}
Java
import java.util.*;
public class Main {
public static boolean findTriplet(int[] arr) {
int n = arr.length;
// Iterate through all possible triplets
for (int i = 0; i < n - 2; i++) {
for (int j = i + 1; j < n - 1; j++) {
for (int k = j + 1; k < n; k++) {
// Check if sum of two elements equals the third element
if (arr[i] + arr[j] == arr[k] || arr[i] + arr[k] == arr[j] || arr[j] + arr[k] == arr[i]) {
return true;
}
}
}
}
return false;
}
// Driver Code with Predefined Input
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
if (findTriplet(arr))
System.out.println("true");
else
System.out.println("false");
}
}
Python
def find_triplet(arr):
n = len(arr)
# Iterate through all possible triplets
for i in range(n - 2):
for j in range(i + 1, n - 1):
for k in range(j + 1, n):
# Check if sum of two elements equals the third element
if arr[i] + arr[j] == arr[k] or arr[i] + arr[k] == arr[j] or arr[j] + arr[k] == arr[i]:
return True
return False
# Driver Code with Predefined Input
arr = [1, 2, 3, 4, 5]
if find_triplet(arr):
print("true")
else:
print("false")
C#
using System;
using System.Linq;
class Program {
static bool FindTriplet(int[] arr) {
int n = arr.Length;
// Iterate through all possible triplets
for (int i = 0; i < n - 2; i++) {
for (int j = i + 1; j < n - 1; j++) {
for (int k = j + 1; k < n; k++) {
// Check if sum of two elements equals the third element
if (arr[i] + arr[j] == arr[k] || arr[i] + arr[k] == arr[j] || arr[j] + arr[k] == arr[i]) {
return true;
}
}
}
}
return false;
}
// Driver Code with Predefined Input
static void Main() {
int[] arr = {1, 2, 3, 4, 5};
if (FindTriplet(arr))
Console.WriteLine("true");
else
Console.WriteLine("false");
}
}
JavaScript
function findTriplet(arr) {
const n = arr.length;
// Iterate through all possible triplets
for (let i = 0; i < n - 2; i++) {
for (let j = i + 1; j < n - 1; j++) {
for (let k = j + 1; k < n; k++) {
// Check if sum of two elements equals the third element
if (arr[i] + arr[j] === arr[k] || arr[i] + arr[k] === arr[j] || arr[j] + arr[k] === arr[i]) {
return true;
}
}
}
}
return false;
}
// Driver Code with Predefined Input
const arr = [1, 2, 3, 4, 5];
if (findTriplet(arr))
console.log("true");
else
console.log("false");
[Better Approach] Sorting with Binary Search for Triplet Finding - O(n^2 * log n) time and O(1) space
This approach first sorts the array and then uses nested loops to iterate over all possible pairs. Instead of using a brute-force third loop, it applies binary search to check if the sum of two elements exists in the remaining array.
C++
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
// Function to perform binary search
bool search(int sum, int start, int end, int arr[])
{
while (start <= end) {
int mid = (start + end) / 2;
if (arr[mid] == sum) {
return true;
}
else if (arr[mid] > sum) {
end = mid - 1;
}
else {
start = mid + 1;
}
}
return false;
}
// Function to check if a triplet exists
bool findTriplet(int arr[], int n)
{
// Sorting the array
sort(arr, arr + n);
// Nested loops to check for pairs
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// Check if the sum exists using binary search
if (search((arr[i] + arr[j]), j + 1, n - 1, arr)) {
return true;
}
}
}
return false;
}
// Driver Code
int main()
{
int arr[] = {5, 32, 1, 7, 10, 50, 19, 21, 2};
int n = sizeof(arr) / sizeof(arr[0]);
cout << (findTriplet(arr, n) ? "true" : "false") << endl;
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
// Comparison function for qsort
int cmp(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
// Function to perform binary search
int search(int sum, int start, int end, int arr[]) {
while (start <= end) {
int mid = (start + end) / 2;
if (arr[mid] == sum) {
return 1;
} else if (arr[mid] > sum) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return 0;
}
// Function to check if a triplet exists
int findTriplet(int arr[], int n) {
// Sorting the array
qsort(arr, n, sizeof(int), cmp);
// Nested loops to check for pairs
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// Check if the sum exists using binary search
if (search(arr[i] + arr[j], j + 1, n - 1, arr)) {
return 1;
}
}
}
return 0;
}
// Driver Code
int main() {
int arr[] = {5, 32, 1, 7, 10, 50, 19, 21, 2};
int n = sizeof(arr) / sizeof(arr[0]);
printf("%s\n", findTriplet(arr, n) ? "true" : "false");
return 0;
}
Java
import java.util.Arrays;
public class TripletFinder {
// Function to perform binary search
public static boolean search(int sum, int start, int end, int[] arr) {
while (start <= end) {
int mid = (start + end) / 2;
if (arr[mid] == sum) {
return true;
} else if (arr[mid] > sum) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return false;
}
// Function to check if a triplet exists
public static boolean findTriplet(int[] arr) {
// Sorting the array
Arrays.sort(arr);
// Nested loops to check for pairs
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
// Check if the sum exists using binary search
if (search(arr[i] + arr[j], j + 1, arr.length - 1, arr)) {
return true;
}
}
}
return false;
}
// Driver Code
public static void main(String[] args) {
int[] arr = {5, 32, 1, 7, 10, 50, 19, 21, 2};
System.out.println(findTriplet(arr) ? "true" : "false");
}
}
Python
def search(sum, start, end, arr):
while start <= end:
mid = (start + end) // 2
if arr[mid] == sum:
return True
elif arr[mid] > sum:
end = mid - 1
else:
start = mid + 1
return False
# Function to check if a triplet exists
def findTriplet(arr):
# Sorting the array
arr.sort()
# Nested loops to check for pairs
n = len(arr)
for i in range(n):
for j in range(i + 1, n):
# Check if the sum exists using binary search
if search(arr[i] + arr[j], j + 1, n - 1, arr):
return True
return False
# Driver Code
arr = [5, 32, 1, 7, 10, 50, 19, 21, 2]
print("true" if findTriplet(arr) else "false")
C#
using System;
using System.Linq;
class TripletFinder {
// Function to perform binary search
static bool Search(int sum, int start, int end, int[] arr) {
while (start <= end) {
int mid = (start + end) / 2;
if (arr[mid] == sum) {
return true;
} else if (arr[mid] > sum) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return false;
}
// Function to check if a triplet exists
static bool FindTriplet(int[] arr) {
// Sorting the array
Array.Sort(arr);
// Nested loops to check for pairs
for (int i = 0; i < arr.Length; i++) {
for (int j = i + 1; j < arr.Length; j++) {
// Check if the sum exists using binary search
if (Search(arr[i] + arr[j], j + 1, arr.Length - 1, arr)) {
return true;
}
}
}
return false;
}
// Driver Code
static void Main() {
int[] arr = {5, 32, 1, 7, 10, 50, 19, 21, 2};
Console.WriteLine(FindTriplet(arr) ? "true" : "false");
}
}
JavaScript
// Function to perform binary search
function search(sum, start, end, arr) {
while (start <= end) {
let mid = Math.floor((start + end) / 2);
if (arr[mid] === sum) {
return true;
} else if (arr[mid] > sum) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return false;
}
// Function to check if a triplet exists
function findTriplet(arr) {
// Sorting the array
arr.sort((a, b) => a - b);
// Nested loops to check for pairs
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
// Check if the sum exists using binary search
if (search(arr[i] + arr[j], j + 1, arr.length - 1, arr)) {
return true;
}
}
}
return false;
}
// Driver Code
let arr = [5, 32, 1, 7, 10, 50, 19, 21, 2];
console.log(findTriplet(arr) ? "true" : "false");
[Expected Approach] Two-Pointer Technique - O(n^2) time and O(1) space
This approach first sorts the array and then uses the two-pointer technique to find a triplet where the sum of two numbers equals the third number. Instead of checking all possible triplets using three loops, it reduces the search space by adjusting two pointers (left
and right
) while iterating through the array. This makes the approach more efficient compared to the naive method.
C++
#include <bits/stdc++.h>
using namespace std;
bool findTriplet(vector<int>& arr) {
int n = arr.size();
// Sort the array
sort(arr.begin(), arr.end());
// Iterate through the array
for (int i = 2; i < n; i++) {
int left = 0, right = i - 1;
while (left < right) {
int sum = arr[left] + arr[right];
if (sum == arr[i])
return true;
else if (sum < arr[i])
left++;
else
right--;
}
}
return false;
}
// Driver Code with Predefined Input
int main() {
vector<int> arr = {1, 2, 3, 4, 5};
if (findTriplet(arr))
cout << "true" << endl;
else
cout << "false" << endl;
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// Function to compare two integers for qsort
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
bool findTriplet(int arr[], int n) {
// Sort the array
qsort(arr, n, sizeof(int), compare);
// Iterate through the array
for (int i = 2; i < n; i++) {
int left = 0, right = i - 1;
while (left < right) {
int sum = arr[left] + arr[right];
if (sum == arr[i])
return true;
else if (sum < arr[i])
left++;
else
right--;
}
}
return false;
}
// Driver Code with Predefined Input
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
if (findTriplet(arr, n))
printf("true\n");
else
printf("false\n");
return 0;
}
Java
// Java implementation to find if there exists a triplet in the array
import java.util.Arrays;
import java.util.List;
public class TripletFinder {
public static boolean findTriplet(List<Integer> arr) {
int n = arr.size();
// Sort the array
Integer[] array = arr.toArray(new Integer[0]);
Arrays.sort(array);
// Iterate through the array
for (int i = 2; i < n; i++) {
int left = 0, right = i - 1;
while (left < right) {
int sum = array[left] + array[right];
if (sum == array[i])
return true;
else if (sum < array[i])
left++;
else
right--;
}
}
return false;
}
// Driver Code with Predefined Input
public static void main(String[] args) {
List<Integer> arr = Arrays.asList(1, 2, 3, 4, 5);
if (findTriplet(arr))
System.out.println("true");
else
System.out.println("false");
}
}
Python
# Function to find if there exists a triplet in the array
def find_triplet(arr):
n = len(arr)
# Sort the array
arr.sort()
# Iterate through the array
for i in range(2, n):
left, right = 0, i - 1
while left < right:
sum = arr[left] + arr[right]
if sum == arr[i]:
return True
elif sum < arr[i]:
left += 1
else:
right -= 1
return False
# Driver Code with Predefined Input
arr = [1, 2, 3, 4, 5]
if find_triplet(arr):
print("true")
else:
print("false")
C#
// C# implementation to find if there exists a triplet in the array
using System;
using System.Collections.Generic;
using System.Linq;
public class TripletFinder
{
public static bool FindTriplet(List<int> arr)
{
int n = arr.Count;
// Sort the array
arr.Sort();
// Iterate through the array
for (int i = 2; i < n; i++)
{
int left = 0, right = i - 1;
while (left < right)
{
int sum = arr[left] + arr[right];
if (sum == arr[i])
return true;
else if (sum < arr[i])
left++;
else
right--;
}
}
return false;
}
// Driver Code with Predefined Input
public static void Main(string[] args)
{
List<int> arr = new List<int> { 1, 2, 3, 4, 5 };
if (FindTriplet(arr))
Console.WriteLine("true");
else
Console.WriteLine("false");
}
}
JavaScript
// JavaScript implementation to find if there exists a triplet in the array
function findTriplet(arr) {
const n = arr.length;
// Sort the array
arr.sort((a, b) => a - b);
// Iterate through the array
for (let i = 2; i < n; i++) {
let left = 0, right = i - 1;
while (left < right) {
const sum = arr[left] + arr[right];
if (sum === arr[i])
return true;
else if (sum < arr[i])
left++;
else
right--;
}
}
return false;
}
// Driver Code with Predefined Input
const arr = [1, 2, 3, 4, 5];
if (findTriplet(arr))
console.log("true");
else
console.log("false");
Similar Reads
Javascript Program to Find a triplet such that sum of two equals to third element Given an array of integers, you have to find three numbers such that the sum of two elements equals the third element.Examples:Input: {5, 32, 1, 7, 10, 50, 19, 21, 2}Output: 21, 2, 19Input: {5, 32, 1, 7, 10, 50, 19, 21, 0}Output: no such triplet existQuestion source: Arcesium Interview Experience |
3 min read
Count triplets such that sum of any two number is equal to third Given an array of distinct positive integers arr[] of length n, the task is to count all the triplets such that the sum of two elements equals the third element.Examples: Input: arr[] = [1, 5, 3, 2] Output: 2 Explanation: In the given array, there are two such triplets such that sum of the two numbe
7 min read
Count of all triplets such that XOR of two equals to third element Given an array arr[] of positive integers, the task is to find the count of all triplets such that XOR of two equals the third element. In other words count all the triplets (i, j, k) such that arr[i] ^ arr[j] = arr[k] and i < j < k. Examples: Input: arr[] = {1, 2, 3, 4}Output: 1Explanation: O
6 min read
Count of triplets from the given Array such that sum of any two elements is the third element Given an unsorted array arr, the task is to find the count of the distinct triplets in which the sum of any two elements is the third element. Examples: Input: arr[] = {1, 3, 4, 15, 19} Output: 2 Explanation: In the given array there are two triplets such that the sum of the two elements is equal to
7 min read
Find three element from given three arrays such that their sum is X | Set 2 Given three sorted integer arrays A[], B[] and C[], the task is to find three integers, one from each array such that they sum up to a given target value X. Print Yes or No depending on whether such triplet exists or not.Examples: Input: A[] = {2}, B[] = {1, 6, 7}, C[] = {4, 5}, X = 12 Output: Yes A
9 min read