Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

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.
All tags
Sort by
Search icon

Interview problems

Java Solution

import java.util.* ;
import java.io.*; 
public class Solution 
{
	public static  ArrayList<Integer> findTriplets(int[] arr, int n) 
    {
	    //Write your code here.
		ArrayList<Integer> list = new ArrayList<>();
		Arrays.sort(arr);
		for(int i = n-1 ; i >= 0 ; i--){
			int j = 0;
			int k = i-1;
			while(j < k){
				int sum = arr[j]+arr[k];
				if(sum == arr[i]){
					list.add(arr[i]);
					list.add(arr[j]);
					list.add(arr[k]);
					return list;
				}else if(sum > arr[i])k--;
				else j++;
			}
		}
		return list;
	}
}
93 views
0 replies
0 upvotes

Interview problems

very easy solution

#include <bits/stdc++.h> 

vector<int> findTriplets(vector<int> &arr, int n) 

{     //Write your code here.

     vector<int> result;

     sort(arr.begin(),arr.end());

     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]){

                 result.push_back(arr[i]);

                 result.push_back(arr[j]);

                 result.push_back(arr[k]);

                 return result;

             }else if(arr[i]>arr[j]+arr[k]){

                 j=j+1;

             }else{

                 k=k-1;

             }

         }

     }

     return result;

     

 

}

181 views
0 replies
0 upvotes

Interview problems

in Java

import java.util.* ;

import java.io.*; 

public class Solution 

{

    public static  ArrayList<Integer> findTriplets(int[] arr, int n) 

    {

        //Write your code here.

        Arrays.sort(arr);

        ArrayList<Integer> res = new ArrayList<>();

        for (int i = arr.length - 1; i >= 0; i--) {

            int left = 0;

            int right = i - 1;

            while (left < right) {

                int sm = arr[left] + arr[right];

                if (sm == arr[i]) {

                  

                    res.add(arr[left]);

                    res.add(arr[right]);

                    res.add(arr[i]);

                    return res;

                } else if (sm < arr[i]) {

                    left++;

                } else {

                    right--;

                }

            }

        }

        return new ArrayList<>();

    }

}

61 views
0 replies
0 upvotes

Interview problems

Can anyone tell what wrong in this code? Bcoz for this code im not getting true output. But in IDE its getting correct output.

public class Solution 

{

    public static  ArrayList<Integer> findTriplets(int[] arr, int n) 

    {

        int sum = 0;

        ArrayList<Integer> ans = new ArrayList<>();

        ArrayList<Integer> soln = new ArrayList<>();

        

        for(int i = 0 ; i < arr.length ; i++){

            ans.add(i,arr[i]);

        }

 

        for(int i = 0 ; i < ans.size()-1 ; i++){

            if(ans.get(i) <= ans.get(i+1)){

                sum = ans.get(i) + ans.get(i+1);

            }

            else{

                sum = ans.get(i) - ans.get(i+1);

            }

 

            if(ans.contains(sum)){

                soln.add(ans.get(i));

                soln.add(ans.get(i+1));

                soln.add(sum);

                break;

            }

        }

        return soln;

    }

}

35 views
0 replies
0 upvotes

Interview problems

Easy solution in C++; please upvote

#include <bits/stdc++.h> 

vector<int> findTriplets(vector<int> &arr, int n) 

{

    //Write your code here.

    

    vector<int> ans;

 

    sort(arr.begin(), arr.end());

 

    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]) {

                ans.push_back(arr[i]);

                ans.push_back(arr[j]);

                ans.push_back(arr[k]);

                return ans;

            }

            else if(arr[i] > arr[j]+arr[k]) {

                j++;

            }

            else {

                k--;

            }

        }

    }

 

    return ans;

 

}

119 views
0 replies
1 upvote

Interview problems

Beats 90% - O(n*log(n)) solution [JAVA] 🌟🌟🌟🌟🌟

 

1. `findTriplets` function takes an array `arr` and its size `n` as input.

2. It sorts the array using `Arrays.sort`, which takes O(n*log(n)) time.

3. It iterates through the sorted array:   - Calls `getTriplet` function with the current element and its index.   - `getTriplet` searches for a pair that sums to the negative of the current element.   - If found, it returns the triplet as an ArrayList.

4. Inside `getTriplet`:   - It iterates through the array from the beginning to the current index.   - Calls `check` function to search for a pair that sums to the target value.   - If found, returns the triplet; otherwise, continues the search.

5. The `check` function searches for a value in the array and returns its index or -1 if not found.

6. Overall time complexity:   - Sorting: O(n*log(n))   - Iterating through the array: O(n)   - Search within `getTriplet` and `check`: O(n) each, but nested.  

7. The dominant factor is sorting, so the overall time complexity is O(n*log(n)).

 

 


import java.util.* ;
import java.io.*; 
public class Solution 
{

     public static int check(int arr[], int sum, int index ){
   int i = 0;
 //   System.out.println("finding pair for "+ sum);
   while(i < index){
    if(arr[i] > sum){
   //   System.out.println("Not found");
     return -1;
    }
    if(arr[i] == sum){
     return i;
    }
    i++;
   }
   return -1;
  }
public static ArrayList<Integer> getTriplet(int arr[], int index, int sum){

 int i = 0;
 // System.out.println("finding MAIN pair for "+ sum);
       ArrayList<Integer> ans = new ArrayList<Integer>();
 int otherIndex = -1;
 while(i < index){
                
    if(arr[i] > sum){
    //  System.out.println("not found");
     ans.clear();
     return ans;
    }
  otherIndex = check(arr,sum-arr[i], i);
  if(otherIndex != -1){
   // System.out.println("Found");
   ans.add(arr[i]);
   ans.add(arr[otherIndex]);
   return ans;
  }
  else{
   // System.out.println("not found for "+ sum);
  }
  i++;
 }
 
 ans.clear();
 return ans;
}
public static  ArrayList<Integer> findTriplets(int[] arr, int n) 
   {
    //Write your code here.
 ArrayList<Integer> triplet = new ArrayList<>();
 Arrays.sort(arr);
       int i= 0;
     try{
   while(i < arr.length){
  triplet = getTriplet(arr,i, arr[i]);
  if(triplet.size() == 2 ){
   triplet.add(arr[i]);
   return triplet;
  }
  i++;
 }
  }
  catch(Exception e){
   System.out.println(e);
  }
       
 return triplet;
}
}

java

229 views
0 replies
0 upvotes

Interview problems

Java two pointers

import java.util.* ;
import java.io.*; 
public class Solution 
{
	public static ArrayList<Integer> findTriplets(int[] arr, int n) 
    {
	    //Write your code here.
        ArrayList<Integer> a=new ArrayList<>();
    Arrays.sort(arr);
    int i=0;
    while(i<n){
      int l=0,r=n-1;
      while(l<r){
      if(arr[i]==arr[l]+arr[r]){
        a.add(arr[i]);
        a.add(arr[l]);
        a.add(arr[r]);
       return a;
      
      }else if(arr[i]<arr[l]+arr[r]) r--;
      else l++;
     }
       i++;
      }
    return a;
	}
}

java

181 views
0 replies
0 upvotes

Interview problems

Python easy sol

from os import *

from sys import *

from collections import *

from math import *

 

def findTriplet(arr,n):

 

    arr.sort()

    for i in range(len(arr)-1,-1,-1):

        left = 0

        right = i-1

        while left<right:

            sum = arr[left] + arr[right]

            if sum == arr[i]:

                return [arr[left],arr[right],arr[i]]

            elif sum < arr[i]:  

                left+=1

            else:

                right-=1

    return []

116 views
0 replies
0 upvotes

Interview problems

Easy And All Solution


#include <bits/stdc++.h> 
vector<int> findTriplets(vector<int> &arr, int n) 
{
    //Write your code here.
    sort(arr.begin(),arr.end());
     int i= 0;
     int j = 1;

    while(i<j && j<n){
        
        int find = arr[i]+arr[j];

        for(int k = j+1 ; k<n ;k++){
            if(arr[k] == find){
                return {arr[i],arr[j],arr[k]};
            }
            else if(arr[k] > find){
               break;
            }
            
           
            }
            if(j==n-1){
                i++;
                j = i+1;
            } else {
                j++;
            }
        }

    

    return {0};
}
*/



#include <bits/stdc++.h>
vector<int> findTriplets(vector<int> &arr, int n) {

 sort(arr.begin(),arr.end());

 for(int k = n-1 ;k>1 ;k--){
     int i = 0;
     int j = k-1;

     while(i<j){
         int sum = arr[i]+arr[j];

         if(sum == arr[k]){
             return {arr[i],arr[j],arr[k]};
         }
         if(sum > arr[k]){
             j--;
         }
         else{
             i++;
         }
     }

 }

return {0};


// Hashing
map<int,int>mp;
    for(int i= 0; i<n; i++) mp[arr[i]]++;

    for(int i=0; i<n; i++){
        bool f = false;
        for(int j = i+1; j<n; j++){
            if(mp[arr[i]+arr[j]] != 0){
                ans.push_back(arr[i]);
                ans.push_back(arr[j]);
                ans.push_back(arr[i]+arr[j]);
                f= true;
                break;
            }
        }

        if(f) break;
    }

    return ans;
}



}

100daysofcode

518 views
0 replies
2 upvotes

Interview problems

Java Solution || Please UpVote Solution || Very basic Solution

public static ArrayList<Integer> findTriplets(int[] arr, int n) {
        ArrayList<Integer> currArr = new ArrayList<>();
        for (int index1 = 0; index1 < n; index1++) {
            for (int index2 = index1 + 1; index2 < n; index2++) {
                for (int index3 = index2 + 1; index3 < n; index3++) {
                    if ((arr[index1] + arr[index2] == arr[index3]) || (arr[index2] + arr[index3] == arr[index1]) || (arr[index3] + arr[index1] == arr[index2])) {
                        currArr.add(arr[index1]);
                        currArr.add(arr[index2]);
                        currArr.add(arr[index3]);

                        return currArr;
                    }
                }
            }
        }
        return currArr;
    }
177 views
0 replies
1 upvote
Full screen
Console