The Wayback Machine - https://web.archive.org/web/20240818163944/https://www.geeksforgeeks.org/find-triplet-sum-two-equals-third-element/
Open In App

Find a triplet such that sum of two equals to third element

Last Updated : 19 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an 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, 19

Input : {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.

Code-

C++




// CPP program to find three numbers
// such that sum of two makes the
// third element in array
#include <bits/stdc++.h>
using namespace std;
  
// Utility function for finding
// triplet in array
void findTriplet(int arr[], int n)
{  
     for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
          for(int k = j + 1; k < n; k++) {
                 if((arr[i]+arr[j]==arr[k]) || (arr[i]+arr[k]==arr[j]) || (arr[j]+arr[k]==arr[i])){
                     // printing out the first triplet
                      cout << "Numbers are: " << arr[i] << " "
                     << arr[j] << " " << arr[k];
                    return; 
                 }
                 
            }
        }
    }
  
    // No such triplet is found in array
    cout << "No such triplet exists";
}
  
// driver program
int main()
{
    int arr[] = { 5, 32, 1, 7, 10, 50, 19, 21, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    findTriplet(arr, n);
    return 0;
}


Java




import java.util.*;
  
public class Main {
  
  // Utility function for finding triplet in array
  public static void findTriplet(int[] arr, int n) {
    for (int i = 0; i < n; i++) {
      for (int j = i + 1; j < n; j++) {
        for(int k = j + 1; k < n; k++) {
          if((arr[i]+arr[j]==arr[k]) || (arr[i]+arr[k]==arr[j]) || (arr[j]+arr[k]==arr[i])) {
  
            // printing out the first triplet
            System.out.println("Numbers are: " + arr[i] + " " + arr[j] + " " + arr[k]);
            return;
          }
        }
      }
    }
    // No such triplet is found in array
    System.out.println("No such triplet exists");
  }
  
  // Driver program
  public static void main(String[] args) {
    int[] arr = { 5, 32, 1, 7, 10, 50, 19, 21, 2 };
    int n = arr.length;
  
    findTriplet(arr, n);
  }
}


Python3




# Python3 program to find three numbers
# such that sum of two makes the
# third element in array
  
# Utility function for finding
# triplet in array
def findTriplet(arr, n):
    for i in range(n):
        for j in range(i + 1, n):
            for k in range(j + 1, n):
                if((arr[i]+arr[j] == arr[k]) or (arr[i]+arr[k] == arr[j]) or (arr[j]+arr[k] == arr[i])):
                    # printing out the first triplet
                    print("Numbers are:", arr[i], arr[j], arr[k])
                    return
  
    # No such triplet is found in array
    print("No such triplet exists")
  
  
# driver program
if __name__ == '__main__':
    arr = [5, 32, 1, 7, 10, 50, 19, 21, 2]
    n = len(arr)
  
    findTriplet(arr, n)


C#




// C# program to find three numbers
// such that sum of two makes the
// third element in array
using System;
  
public class MainClass {
    // Utility function for finding
    // triplet in array
    public static void FindTriplet(int[] arr, int n)
    {
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                for (int k = j + 1; k < n; k++) {
                    if ((arr[i] + arr[j] == arr[k])
                        || (arr[i] + arr[k] == arr[j])
                        || (arr[j] + arr[k] == arr[i])) {
                        // printing out the first triplet
                        Console.WriteLine(
                            "Numbers are: " + arr[i] + " "
                            + arr[j] + " " + arr[k]);
                        return;
                    }
                }
            }
        }
  
        // No such triplet is found in array
        Console.WriteLine("No such triplet exists");
    }
  
    public static void Main()
    {
        int[] arr = { 5, 32, 1, 7, 10, 50, 19, 21, 2 };
        int n = arr.Length;
  
        FindTriplet(arr, n);
    }
}


Javascript




// Utility function for finding triplet in array
function findTriplet(arr) {
  const n = arr.length;
  
  for (let i = 0; i < n; i++) {
    for (let j = i + 1; j < n; j++) {
      for (let k = j + 1; k < n; k++) {
        if (
          arr[i] + arr[j] === arr[k] ||
          arr[i] + arr[k] === arr[j] ||
          arr[j] + arr[k] === arr[i]
        ) {
          // Printing out the first triplet
          console.log(`Numbers are: ${arr[i]}, ${arr[j]}, ${arr[k]}`);
          return;
        }
      }
    }
  }
  
  // No such triplet is found in array
  console.log("No such triplet exists");
}
  
// Driver program
const arr = [5, 32, 1, 7, 10, 50, 19, 21, 2];
findTriplet(arr);


Output

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.  

  • Sort the given array first.
  • Start fixing the greatest element of three from the back and traverse the array to find the other two numbers which sum up to the third element.
  • Take two pointers j(from front) and k(initially i-1) to find the smallest of the two number and from i-1 to find the largest of the two remaining numbers
  • If the addition of both the numbers is still less than A[i], then we need to increase the value of the summation of two numbers, thereby increasing the j pointer, so as to increase the value of A[j] + A[k].
  • If the addition of both the numbers is more than A[i], then we need to decrease the value of the summation of two numbers, thereby decrease the k pointer so as to decrease the overall value of A[j] + A[k].

Below image is a dry run of the above approach: 

Below is the implementation of the above approach: 

C++




// CPP program to find three numbers
// such that sum of two makes the
// third element in array
#include <bits/stdc++.h>
using namespace std;
  
// Utility function for finding
// triplet in array
void findTriplet(int arr[], int n)
{
    // sort the array
    sort(arr, arr + n);
  
    // for every element in arr
    // check if a pair exist(in array) whose
    // sum is equal to arr element
    for (int i = n - 1; i >= 0; i--) {
        int j = 0;
        int k = i - 1;
  
        // Iterate forward and backward to find
        // the other two elements
        while (j < k) {
  
            // If the two elements sum is
            // equal to the third element
            if (arr[i] == arr[j] + arr[k]) {
  
                // pair found
                cout << "numbers are " << arr[i] << " "
                     << arr[j] << " " << arr[k] << endl;
                return;
            }
  
            // If the element is greater than
            // sum of both the elements, then try
            // adding a smaller number to reach the
            // equality
            else if (arr[i] > arr[j] + arr[k])
                j += 1;
  
            // If the element is smaller, then
            // try with a smaller number
            // to reach equality, so decrease K
            else
                k -= 1;
        }
    }
  
    // No such triplet is found in array
    cout << "No such triplet exists";
}
  
// driver program
int main()
{
    int arr[] = { 5, 32, 1, 7, 10, 50, 19, 21, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    findTriplet(arr, n);
    return 0;
}


Java




// Java program to find three numbers
// such that sum of two makes the
// third element in array
import java.util.Arrays;
  
public class GFG {
  
    // utility function for finding
    // triplet in array
    static void findTriplet(int arr[], int n)
    {
        // sort the array
        Arrays.sort(arr);
  
        // for every element in arr
        // check if a pair exist(in array) whose
        // sum is equal to arr element
        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]) {
  
                    // pair found
                    System.out.println("numbers are " + arr[i] + " "
                                       + arr[j] + " " + arr[k]);
  
                    return;
                }
                else if (arr[i] > arr[j] + arr[k])
                    j += 1;
                else
                    k -= 1;
            }
        }
  
        // no such triplet is found in array
        System.out.println("No such triplet exists");
    }
  
    // driver program
    public static void main(String args[])
    {
        int arr[] = { 5, 32, 1, 7, 10, 50, 19, 21, 2 };
        int n = arr.length;
        findTriplet(arr, n);
    }
}
// This code is contributed by Sumit Ghosh


Python




# Python program to find three numbers
# such that sum of two makes the
# third element in array
  
# utility function for finding
# triplet in array
def findTriplet(arr, n):
      
    # sort the array
    arr.sort()
   
    # for every element in arr
    # check if a pair exist(in array) whose
    # sum is equal to arr element
    i = n - 1
    while(i >= 0):
        j = 0
        k = i - 1
        while (j < k):
            if (arr[i] == arr[j] + arr[k]):
                 
                # pair found
                print "numbers are ", arr[i], arr[j], arr[k]
                return
            elif (arr[i] > arr[j] + arr[k]):
                j += 1
            else:
                k -= 1
        i -= 1
          
    # no such triplet is found in array
    print "No such triplet exists"
   
# driver program
arr = [ 5, 32, 1, 7, 10, 50, 19, 21, 2 ]
n = len(arr)
findTriplet(arr, n)
  
# This code is contributed by Sachin Bisht


C#




// C# program to find three numbers
// such that sum of two makes the
// third element in array
using System;
  
public class GFG {
  
    // utility function for finding
    // triplet in array
    static void findTriplet(int[] arr, int n)
    {
  
        // sort the array
        Array.Sort(arr);
  
        // for every element in arr
        // check if a pair exist(in
        // array) whose sum is equal
        // to arr element
        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]) {
  
                    // pair found
                    Console.WriteLine("numbers are "
                                      + arr[i] + " " + arr[j]
                                      + " " + arr[k]);
  
                    return;
                }
                else if (arr[i] > arr[j] + arr[k])
                    j += 1;
                else
                    k -= 1;
            }
        }
  
        // no such triplet is found in array
        Console.WriteLine("No such triplet exists");
    }
  
    // driver program
    public static void Main()
    {
        int[] arr = { 5, 32, 1, 7, 10, 50,
                      19, 21, 2 };
        int n = arr.Length;
  
        findTriplet(arr, n);
    }
}
  
// This code is contributed by vt_m.


PHP




<?php
// PHP program to find three
// numbers such that sum of 
// two makes the third
// element in array
  
// utility function for 
// finding triplet in array
function findTriplet($arr, $n)
{
    // sort the array
    sort($arr);
  
    // for every element in 
    // arr check if a pair 
    // exist(in array) whose
    // sum is equal to arr element
    for ($i = $n - 1; $i >= 0; $i--)
    {
        $j = 0;
        $k = $i - 1;
        while ($j < $k) 
        {
            if ($arr[$i] == $arr[$j] + $arr[$k]) 
            {
                  
                // pair found
                echo "numbers are ", $arr[$i], " ", 
                                      $arr[$j], " ", 
                                      $arr[$k];
                return;
            } 
            else if ($arr[$i] > $arr[$j] + 
                                $arr[$k])
                $j += 1;
            else
                $k -= 1;
        }
    }
  
    // no such triplet 
    // is found in array
    echo "No such triplet exists";
}
  
// Driver Code
$arr = array(5, 32, 1, 7, 10, 
             50, 19, 21, 2 );
$n = count($arr);
  
findTriplet($arr, $n);
  
// This code is contributed by anuj_67.
?>


Javascript




<script>
  
// Javascript program to find three numbers
// such that sum of two makes the
// third element in array
  
  
// Utility function for finding
// triplet in array
function findTriplet(arr, n)
{
    // sort the array
    arr.sort((a,b) => a-b);
  
    // for every element in arr
    // check if a pair exist(in array) whose
    // sum is equal to arr element
    for (let i = n - 1; i >= 0; i--) {
        let j = 0;
        let k = i - 1;
  
        // Iterate forward and backward to find
        // the other two elements
        while (j < k) {
  
            // If the two elements sum is
            // equal to the third element
            if (arr[i] == arr[j] + arr[k]) {
  
                // pair found
                document.write("numbers are " + arr[i] +
                " " + arr[j] + " " + arr[k] + "<br>");
                return;
            }
  
            // If the element is greater than
            // sum of both the elements, then try
            // adding a smaller number to reach the
            // equality
            else if (arr[i] > arr[j] + arr[k])
                j += 1;
  
            // If the element is smaller, then
            // try with a smaller number
            // to reach equality, so decrease K
            else
                k -= 1;
        }
    }
  
    // No such triplet is found in array
    document.write("No such triplet exists");
}
  
// driver program
  
    let arr = [ 5, 32, 1, 7, 10, 50, 19, 21, 2 ];
    let n = arr.length;
  
    findTriplet(arr, n);
  
// This code is contributed by Mayank Tyagi
  
</script>


Output

numbers are 21 2 19

Time Complexity: O(N^2)
Auxiliary Space: O(1)

Another Approach: The idea is similar to previous approach:

  1. Sort the given array.
  2. 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).
  3. Take the sum of both the elements and search it in the remaining array using Binary Search.

Implementation:

C++




// CPP program to find three numbers
// such that sum of two makes the
// third element in array
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
  
// function to perform binary search
bool search(int sum, int start, int end, int arr[])
{
    while (start <= end) {
        int mid = (start + end) / 2;
        if (arr[mid] == sum) {
            return true;
        }
        else if (arr[mid] > sum) {
            end = mid - 1;
        }
        else {
            start = mid + 1;
        }
    }
    return false;
}
  
// function to find the triplets
void findTriplet(int arr[], int n)
{
    // sorting the array
    sort(arr, arr + n);
  
    // initialising nested loops
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
  
            // finding the sum of the numbers
            if (search((arr[i] + arr[j]), j, n - 1, arr)) {
  
                // printing out the first triplet
                cout << "Numbers are: " << arr[i] << " "
                     << arr[j] << " " << (arr[i] + arr[j]);
                return;
            }
        }
    }
    // if no such triplets are found
    cout << "No such numbers exist" << endl;
}
  
int main()
{
    int arr[] = { 5, 32, 1, 7, 10, 50, 19, 21, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    findTriplet(arr, n);
    return 0;
}
  
// This code is contributed by Sarthak Delori


Java




// Java program to find three numbers
// such that sum of two makes the
// third element in array
import java.util.*;
  
class GFG{
  
// Function to perform binary search
static boolean search(int sum, int start, 
                      int end, int arr[])
{
    while (start <= end) 
    {
        int mid = (start + end) / 2;
        if (arr[mid] == sum) 
        {
            return true;
        }
        else if (arr[mid] > sum)
        {
            end = mid - 1;
        }
        else
        {
            start = mid + 1;
        }
    }
    return false;
}
  
// Function to find the triplets
static void findTriplet(int arr[], int n)
{
      
    // Sorting the array
    Arrays.sort(arr);
  
    // Initialising nested loops
    for(int i = 0; i < n; i++) 
    {
        for(int j = i + 1; j < n; j++) 
        {
              
            // Finding the sum of the numbers
            if (search((arr[i] + arr[j]), j, n - 1, arr)) 
            {
                  
                // Printing out the first triplet
                System.out.print("Numbers are: " + arr[i] + " " + 
                                   arr[j] + " " + (arr[i] + arr[j]));
                return;
            }
        }
    }
      
    // If no such triplets are found
    System.out.print("No such numbers exist");
}
  
// Driver code
public static void main(String args[])
{
    int arr[] = { 5, 32, 1, 7, 10, 50, 19, 21, 2 };
    int n = arr.length;
      
    findTriplet(arr, n);
}
}
  
// This code is contributed by target_2


Python3




# Python program to find three numbers
# such that sum of two makes the
# third element in array
from functools import cmp_to_key
  
def mycmp(a, b):
    return a - b 
  
def search(sum, start, end, arr):
  
    while (start <= end):
        mid = (start + end) // 2
        if (arr[mid] == sum):
            return True
        elif (arr[mid] > sum):
            end = mid - 1
        else:
            start = mid + 1
  
    return False
  
# Utility function for finding
# triplet in array
def findTriplet(arr, n):
  
    # sort the array
    arr.sort(key = cmp_to_key(mycmp))
  
    # initialising nested loops
    for i in range(n):
        for j in range(i + 1,n):
            if (search((arr[i] + arr[j]), j, n - 1, arr)):
                print(f"numbers are {arr[i]} {arr[j]} {( arr[i] + arr[j] )}")
                return
  
    # No such triplet is found in array
    print("No such triplet exists")
  
# driver program
arr = [ 5, 32, 1, 7, 10, 50, 19, 21, 2 ]
n = len(arr)
  
findTriplet(arr, n)
  
# This code is contributed by shinjanpatra


C#




// C# program to find three numbers
// such that sum of two makes the
// third element in array
using System;
public class GFG {
  
  // function to perform binary search
  static bool search(int sum, int start, int end, int [] arr)
  {
    while (start <= end) {
      int mid = (start + end) / 2;
      if (arr[mid] == sum) {
        return true;
      }
      else if (arr[mid] > sum) {
        end = mid - 1;
      }
      else {
        start = mid + 1;
      }
    }
    return false;
  }
  
  // utility function for finding
  // triplet in array
  static void findTriplet(int[] arr, int n)
  {
  
    // sort the array
    Array.Sort(arr);
  
    // for every element in arr
    // check if a pair exist(in
    // array) whose sum is equal
    // to arr element
    for (int i = 0; i < n; i++) {
      for(int j=i+1;j<n;j++)
      {
        // finding the sum of the numbers
        if (search((arr[i] + arr[j]), j, n - 1, arr)) {
  
          // pair found
          Console.WriteLine("Numbers are "
                            + arr[i] + " " + arr[j]
                            + " " + (arr[i]+arr[j]));
          return;
        }
      }
    }    
  
    // no such triplet is found in array
    Console.WriteLine("No such triplet exists");
  }
  
  // driver program
  public static void Main()
  {
    int[] arr = { 5, 32, 1, 7, 10, 50,
                 19, 21, 2 };
    int n = arr.Length;
  
    findTriplet(arr, n);
  }
}
  
// This code is contributed by Aarti_Rathi


Javascript




<script>
  
// Javascript program to find three numbers
// such that sum of two makes the
// third element in array
bool search(sum, start, end, arr)
{
    while (start <= end) {
        let mid = (start + end) / 2;
        if (arr[mid] == sum) {
            return true;
        }
        else if (arr[mid] > sum) {
            end = mid - 1;
        }
        else {
            start = mid + 1;
        }
    }
    return false;
}
  
// Utility function for finding
// triplet in array
function findTriplet(arr, n)
{
    // sort the array
    arr.sort((a,b) => a-b);
  
    // initialising nested loops
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
            if (search((arr[i] + arr[j]), j, n - 1, arr)) {
                document.write("numbers are " + arr[i] +
                " " + arr[j] + " " + ( arr[i] + arr[j] ) + "<br>");
            }
        }
    }
    // No such triplet is found in array
    document.write("No such triplet exists");
}
  
// driver program
    let arr = [ 5, 32, 1, 7, 10, 50, 19, 21, 2 ];
    let n = arr.length;
  
    findTriplet(arr, n);
  
// This code is contributed by Sarthak Delori
</script>


Output

Numbers are: 2 5 7

Time Complexity: O(N^2*log N)
Auxiliary Space: O(1)



Similar Reads

Javascript Program to Find a triplet such that sum of two equals to third element
Given an 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, 19 Input: {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) Recommended:
5 min read
Count of all triplets such that XOR of two equals to third element
Given an array arr[] of positive integers, the task is to find the count of all triplets such that XOR of two equals the third element. In other words count all the triplets (i, j, k) such that arr[i] ^ arr[j] = arr[k] and i &lt; j &lt; k. Examples: Input: arr[] = {1, 2, 3, 4}Output: 1Explanation: One such triplet exists in this i.e {1, 2, 3} where
6 min read
Find a triplet (X, Y, Z) with given sum as N and GCD of two numbers is the third number
Given a positive integer N, the task is to find a triple of three distinct positive integers (X, Y, Z) such that X + Y + Z = N and X = GCD (Y, Z). Example: Input: N = 12Output:1 2 9Explanation: The triplet (1, 2, 9) is set of distinct integers such that 1 + 2 + 9 = 12 and 1 = GCD(2, 9). Input: N = 5675Output:1 3 5671 Naive Approach: The basic idea
8 min read
Count triplets from a given range having sum of two numbers of a triplet equal to the third number
Given two integers L and R, the task is to find the number of unique triplets whose values lie in the range [L, R], such that the sum of any two numbers is equal to the third number. Examples: Input: L = 1, R = 3Output: 3Explanation: Three such triplets satisfying the necessary conditions are (1, 1, 2), (1, 2, 3) and (2, 1, 3). Input: L = 2, R = 6O
9 min read
Check if a triplet of buildings can be selected such that the third building is taller than the first building and smaller than the second building
Given an array arr[] consisting of N integers, where each array element represents the height of a building situated on the X co-ordinates, the task is to check if it is possible to select 3 buildings, such that the third selected building is taller than the first selected building and shorter than the second selected building. Examples: Input: arr
12 min read
Find triplet (A, B, C) such that LCM(A, B) + LCM(A, C) + LCM(B, C) equals N
Given an integer N. Find a triplet let say {A, B, C} such that LCM(A, B) + LCM(B, C) + LCM(A, C) = N. If no possible triplets are there, output -1 instead. Examples: Input: N = 1Output: -1Explanation: No possible triplets are there. Input: N = 15Output: 5 5 5Explanation: LCM(5, 5) + LCM(5, 1) + LCM(5, 1) = 5 + 5 + 5 = 15. Observations: Observation
8 min read
Check if every vertex triplet in graph contains two vertices connected to third vertex
Given an undirected graph with N vertices and K edges, the task is to check if for every combination of three vertices in the graph, there exists two vertices which are connected to third vertex. In other words, for every vertex triplet (a, b, c), if there exists a path between a and c, then there should also exist a path between b and c. Examples:
9 min read
Count triplet of indices (i, j, k) such that XOR of elements between [i, j) equals [j, k]
Given an array of integers Arr. The task is to count the number of triplets (i, j, k) such that Ai ^ Ai+1 ^ Ai+2 ^ .... ^ Aj-1 = Aj ^ Aj+1 ^ Aj+2 ^ ..... ^ Ak, and 0 &lt; (i, j, k) &lt; N , where N is the size of the array.Where ^ is the bitwise xor of two numbers. Examples: Input: Arr = [5, 2, 7] Output: 2 Explanation: The triplets are (0, 2, 2) s
6 min read
Count of triplets from the given Array such that sum of any two elements is the third element
Given an unsorted array arr, the task is to find the count of the distinct triplets in which the sum of any two elements is the third element. Examples: Input: arr[] = {1, 3, 4, 15, 19} Output: 2 Explanation: In the given array there are two triplets such that the sum of the two elements is equal to the third element: {{1, 3, 4}, {4, 15, 19}} Input
7 min read
Count triplets such that sum of any two number is equal to third | Set 2
Given an array of distinct positive integers arr[] of length N, the task is to count all the triplets such that the sum of two elements equals the third element. Examples: Input: arr[] = {1, 5, 3, 2} Output: 2 Explanation: In the given array, there are two such triplets such that sum of the two numbers is equal to the third number, those are - (1,
9 min read
Count distinct prime triplets up to N such that sum of two primes is equal to the third prime
Given an integer N, the task is to count the number of distinct prime triplets (a, b, c) from the range [1, N] such that a &lt; b &lt; c ? N and a + b = c.Note: Two prime tuples are distinct if at least one of the primes present in them are different. Examples: Input: N = 6Output: 1Explanation: Among numbers in the range [1, 6], the only prime trip
6 min read
Find third number such that sum of all three number becomes prime
Given two numbers A and B. The task is to find the smallest positive integer greater than or equal to 1 such that the sum of all three numbers become a prime number.Examples: Input: A = 2, B = 3 Output: 2 Explanation: The third number is 2 because if we add all three number the sum obtained is 7 which is a prime number.Input: A = 5, B = 3 Output: 3
5 min read
Count triplets such that product of two numbers added with third number is N
Given a positive integer N, the task is to find the number of triplets (A, B, C) where A, B, C are positive integers such that the product of two numbers added with the third number is N i.e., A * B + C = N. Examples: Input: N = 3Output: 3Explanation:Following are the possible triplets satisfying the given criteria: (1, 1, 2): The value of 1*1 + 2
7 min read
Check if two circles intersect such that the third circle passes through their points of intersections and centers
Given centres and the radii of three circles A, B, and C in the form of {X, Y, R}, where (X, Y) is the centre of the circle and R is the radius of that circle. The task is to check if any two circles intersect such that the third circle passes through the intersecting points and the centres of the two circles. If found to be true, then print "Yes".
9 min read
Split array to three subarrays such that sum of first and third subarray is equal and maximum
Given an array of N integers, the task is to print the sum of the first subarray by splitting the array into exactly three subarrays such that the sum of the first and third subarray elements are equal and the maximum. Note: All the elements must belong to a subarray and the subarrays can also be empty. Examples: Input: a[] = {1, 3, 1, 1, 4} Output
13 min read
Find non-decreasing array brr[] of size 2*N such that each arr[i] equals sum of brr[i] and brr[2*n – i +1]
Given an array arr[] of size N, the task is to find another array brr[] of size 2*N such that it is non-decreasing and for each ith from 1 to N arr[i] = brr[i] + brr[2*n - i +1]. Examples: Input: n = 2, arr[] = { 5, 6 }Output: 0 1 5 5Explanation: For i =1, arr[1] = 5, brr[1]+brr[2*2-1+1] = 5, so both are equal, For i =2, arr[2] = 6, brr[2]+brr[2*2-
7 min read
Find the range [L, R] such that sum of numbers in this range equals to N
Given an integer N (N ≠ 0), the task is to find a range [L, R] (−10âŧÂđâļ &lt; L &lt; R &lt; 10Âđâļ) such that sum of all integers in this range is equal to N. L + (L+1) + â€Ķ + (R−1) + R = N Examples: Input : N = 3Output: -2 3Explanation: For L = -2 and R = -3 the sum becomes -2 + (-1) + 0 + 1 + 2 + 3 = 3 Input : N = -6Output: -6 5Explanation: The sum fo
5 min read
Puzzle | Place numbers 1 to 9 in a Circle such that sum of every triplet in straight line is 15
Place the numbers 1 to 9 in a circle, so that wherever there are three in a straight line they shall add up to 15. SOLUTION:[video mp4="https://media.geeksforgeeks.org/wp-content/uploads/20200710130155/wpv.mp4"][/video]The sum of first number and last number is ten ( 1 + 9 = 10 ).Similarly, the sum of second number and second last element is also t
2 min read
Find triplet such that number of nodes connecting these triplets is maximum
Given a Tree with N nodes, the task is to find a triplet of nodes (a, b, c) such that the number of nodes covered in the path connecting these nodes is maximum. (Count a node only once).Examples: Input: N = 4 Edge Set: 1 2 1 3 1 4 Output: (2, 3, 4) (2, 3, 4) as path between (2, 3) covers nodes 2, 1, 3 and path between (3, 4) covers nodes 3, 1, 4. H
13 min read
Find a triplet in an array such that arr[i] arr[k] and i &lt; j &lt; k
Given an array arr[] consisting of a permutation of first N natural numbers, the task is to find a triplet (i, j, k) from the given array such that arr[i] &lt; arr[j] &gt; arr[k], where (i &lt; j &lt; k). If multiple triplets exist, then print any valid triplet of indices. Otherwise, print -1. Examples: Input: arr[] = {2, 1, 4, 3} Output: 1 2 3 Exp
6 min read
Find a triplet (i, j, k) from an array such that i &lt; j &lt; k and arr[i] &lt; arr[j] &gt; arr[k]
Given an array arr[] which consists of a permutation of first N natural numbers, the task is to find any triplet (i, j, k) from the given array such that 0 ? i &lt; j &lt; k ? (N - 1) and arr[i] &lt; arr[j] and arr[j] &gt; arr[k]. If no such triplet exists, then print "-1". Examples: Input: arr[] = {4, 3, 5, 2, 1, 6}Output: 1 2 3Explanation: For th
5 min read
Find a triplet (A, B, C) such that 3*A + 5*B + 7*C is equal to N
Given an integer N, the task is to find three positive integers A, B, and C such that the value of the expression (3*A + 5*B + 7*C) is equal to N. If no such triplet exists, then print "-1". Examples: Input: N = 19Output:A = 3B = 2C = 0Explanation: Setting A, B, and C equal to 0, 1, and 2 respectively, the evaluated value of the expression = 3 * A
6 min read
Find a triplet (X, Y, Z) such that all are divisible by A, exactly one is divisible by both A and B, and X + Y = Z
Given two integers A and B, the task is to find a triplet (X, Y, Z) such that all of them are divisible by A, exactly one of them is divisible by both A and B, and X + Y = Z. Example: Input: A = 5, B = 3Output: 10 50 60Explanation: For the triplet (10, 50, 60), all of them are divisible by 5, 60 is divisible by both 5 and 3, and 10 + 50 = 60. There
4 min read
Count prime triplets upto N having sum of first two elements equal to the third number
Given an integer N, the task is to find the number of distinct prime triplets from the range [1, N] having the sum of the first two numbers equal to the third number. Examples: Input: N = 7Output: 2Explanation: All valid triplets are (2, 3, 5) and (2, 5, 7). Therefore, the required output is 2. Input: N = 4Output: 0 Approach: The idea is to use Sie
6 min read
Count of triplets having sum of product of any two numbers with the third number equal to N
Given an positive integer N, the task is to find the number of triplets (X, Y, Z) such that the sum of product of any two numbers with the third number is N. Examples: Input: N = 2Output: 1Explanation:The only triplets satisfying the given criteria is (1, 1, 1). Therefore, the count is 1. Input: N = 3Output: 3 Approach: This given problem can be so
11 min read
Count of equal value pairs from given two Arrays such that a[i] equals b[j]
Given two arrays a[] and b[] of length N and M respectively, sorted in non-decreasing order. The task is to find the number of pairs (i, j) such that, a[i] equals b[j]. Examples: Input: a[] = {1, 1, 3, 3, 3, 5, 8, 8}, b[] = {1, 3, 3, 4, 5, 5, 5}Output: 11Explanation: Following are the 11 pairs with given condition The 11 pairs are {{1, 1}, {1, 1},
14 min read
Triplet with no element divisible by 3 and sum N
Given an integer N greater than 2, the task is to print any combination of a, b and c such that: a + b + c = Na, b and c are not divisible by 3. Examples: Input: N = 233 Output: 77 77 79 Input: N = 3 Output: 1 1 1 A naive approach is to use three loops and check for the given condition. Below is the implementation of the above approach: C/C++ Code
8 min read
Find if 0 is removed more or 1 by deleting middle element if consecutive triplet is divisible by 3 in given Binary Array
Given a binary array a[] of size N of 1's and 0's. The task is to remove an element if a[i-1]+a[i]+a[i+1] is divisible by 3. Print 1 if more number of 1's are removed than 0, otherwise print 0. Examples: Input: a[] = { 1, 1, 1, 0, 1, 0, 0}Output: 1Explanation: Remove the second 1 from the left since that is the only '1' for which (a[i]+a[i-1]+a[i+1
5 min read
Check if minimum element in array is less than or equals half of every other element
Given an array arr[], the task is to check if the minimum element in the array is less than or equal to half of every other element. If it is then print "yes" otherwise print "no".Note: The minimum number in the given array is always unique. Examples: Input: arr = {2, 1, 4, 5} Output: Yes Explanation: 1 is the minimum element in the array arr[] and
11 min read
Find the number of pairs such that their gcd is equals to 1
Given an array a of size N. The task is to find the number of pairs such that gcd(a[i], a[j]) is equal to 1, where 1 ? i &lt; j ? N. Examples: Input : a[] = {1, 2, 4, 6} Output : 3 {1, 2}, {1, 4}, {1, 6} are such pairs Input : a[] = {1, 2, 3, 4, 5, 6} Output : 11 Approach : The answer is to sum of ?(X) * C(D(X), 2) overall integer X. Where, ?(X) is
10 min read
three90RightbarBannerImg