![]() |
VOOZH | about |
Write a C++ program for a given 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 exist
Question source: Arcesium Interview Experience | Set 7 (On campus for Internship)
Simple approach:
Run three loops and check if there exists a triplet such that sum of two elements equals the third element.
Below is the implementation of the above approach:
Numbers are: 5 7 2
Time complexity: O(n^3)
Auxiliary Space: O(1)
Efficient approach:
The idea is similar to Find a triplet that sum to a given value.
Step-by-step approach:
Below image is a dry run of the above approach:
Below is the implementation of the above approach:
Output:
numbers are 21 2 19
Time complexity: O(N^2)
Auxiliary Space: O(1)
- Sort the given array.
- Start a nested loop, fixing the first element i(from 0 to n-1) and moving the other one j (from i+1 to n-1).
- Take the sum of both the elements and search it in the remaining array using Binary Search.
Below is the implementation of the above approach:
Time Complexity: O(N^2*log N)
Auxiliary Space: O(1)
Please refer complete article on Find a triplet such that sum of two equals to third element for more details!