- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find a triplet such that sum of two equals to third element in C++
Suppose there is an array of n numbers. We have to find three numbers, such that sum of two elements is same as the third one. So if the array is like [5, 32, 1, 7, 10, 50, 19, 21, 2], the output will be 21, 2, 19. If no such element has found, display that message.
To solve this, we will follow some steps as follows −
Sort the given array
Then start fixing the greatest element from the last element and traverse the array to find other two numbers which sum up to the third element.
Take two pointers j and k, j is from first, k is from last to find the smallest of two numbers from i - 1 to find the largest of the two remaining numbers.
If the addition of both the numbers is still less than Arr[i], then we have to increase the value of the summation of two numbers, thereby increase the j pointer, so as to increase the value of Arr[j] + Arr[k]
If the addition of both the numbers is more than Arr[i], then we need to decrease the value of the summation of two numbers, thereby decrease the pointer k, such that decrease the overall value of Arr[j] + Arr[k]
Example
#include<iostream> #include<algorithm> #define N 5 using namespace std; void getValueTriplet(int arr[], int n) { sort(arr, arr + n); for (int i = n - 1; i >= 0; i--) { int j = 0; int k = i - 1; while (j < k) { if (arr[i] == arr[j] + arr[k]) { cout << "The numbers are " << arr[i] << " " << arr[j] << " " << arr[k] << endl; return; } else if (arr[i] > arr[j] + arr[k]) j += 1; else k -= 1; } } cout << "No such triplet exists"; } int main() { int arr[] = { 5, 32, 1, 7, 10, 50, 19, 21, 2 }; int n = sizeof(arr) / sizeof(arr[0]); getValueTriplet(arr, n); }
Output
The numbers are 21 2 19