Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Triplet that sum to a given value

triplet that sum to given value

Triplet that sum to a given value in Java

Problem statement:

Given an array and a value, find if there is a triplet in array whose sum is equal to the given value. If there is such a triplet present in array, then print the triplet and return true. Else return false. 

Input: array = {1, 2, 3, 4, 5}, sum = 9

Output: 5, 3, 1

Explanation: There is a triplet (5, 3 and 1) present in the array whose sum is 9.

Algorithm:

  • Take  an array of length n and a sum s
  • Create three nested loop first loop runs from start to end (loop counter i), the second loop runs from i+1 to end (loop counter j) and the third loop runs from j+1 to end (loop counter k)
  • The counter of these loops represents the index of 3 elements of the triplets.
  • Find the sum of the ith, jth and kth element. If the sum is equal to a given sum. Print the triplet and break.
  • If there is no triplet, then print that no triplet exists.

Java code :

// Java program to find a triplet 
class prepinsta { 

    
    boolean findnumbers(int A[], int arrsizeint sum
    { 
        int lr

        
        for (int i = 0; i < arrsize – 2; i++) { 

            
            for (int j = i + 1; j < arrsize – 1; j++) { 

                
                for (int k = j + 1; k < arrsize; k++) { 
                    if (A[i] + A[j] + A[k] == sum) { 
                        System.out.print(“Triplet is “ + A[i] + “, “ + A[j] + “, “ + A[k]); 
                        return true
                    } 
                } 
            } 
        } 

        //no triplet
        return false
    } 

    
    public static void main(String[] args
    { 
        prepinsta triplet = new prepinsta(); 
        int A[] = {12345}; 
        int sum = 9
        int arrsize = A.length

        triplet.findnumbers(A, arrsize, sum); 
    } 
Output:

Triplet is 5, 3, 1