Sum of Two Elements Equals the Third.

Easy
0/40
Average time to solve is 10m
profile
Contributed by
30 upvotes
Asked in companies
HSBCBarclaysJio Platforms Limited

Problem statement

You are given an array Arr consisting of n integers, you need to find a valid triplet as explained below.

An array is said to have a valid triplet {arr[i], arr[j], arr[k]} if there exists three indices i, j and k such that i != j, j != k and i != j and arr[i] + arr[j] = arr[k] or arr[i] + arr[k] = arr[j] or arr[k] + arr[j] = arr[i].

For Example:
Arr = 10, 5, 5, 6, 2, 
In this array, the triplet {10, 5, 5} is valid triplet because, 5 + 5 = 10.

Note:

The elements in the array need not be distinct.
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of the input contains an integer T, denoting the number of test cases.

The first line of each test case contains the integer N, denoting the size of the array.

The second line of each test case contains N space-separated integers denoting the array elements.
Output Format:
For each test case, every line of output contains “true” if there is a valid triplet and the user has returned a valid one, else "false" will be printed. 

Note :

You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <=  50
1 <= N <= 10^3  
1 <= Arr[i] <= 10^4   

Time Limit: 1 sec
Sample Input 1:
2
4
1 1 1 1
5
10 5 5 6 2
Sample Output 1:
false
true
Explanation For Sample Input 1:
In the first case, no valid triplet can be formed.

5 5 10 is the triplet in which the sum of two elements {5,5} is equal to the third {10}.
Sample Input 2:
2
6
1 2 3 1 2 3
6
1 1 2 2 1 1
Sample Output 2:
 true
 true
Hint

Try all possible combinations.

Approaches (2)
Brute Force
  • The most trivial approach would be to find any triplet in the array such that two of it’s elements sums up to the third element.
  • We can find the answer using three nested loops for three different indexes and check if the values at those indexes can yield the required triplet.
  • If for distinct indices we find the required triplet, return the answer list containing the three elements in it.
  • If after iterating all the loops, no such triplet is found, return an empty list.
Time Complexity

O(N ^ 3), where N is the number of elements in the array.

 

Since we are iterating the complete range three times for getting the triplets and then finding their sum, the time complexity is O(N ^ 3).

Space Complexity

O(1)

 

Since we are using constant extra memory.

Code Solution
(100% EXP penalty)
Sum of Two Elements Equals the Third.
Full screen
Console