Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Find a triplet such that sum of two equals to third element
Next article icon

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

Last Updated : 16 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.
Time complexity: O(n^3)

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:

JavaScript
// 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                 console.log("numbers are " + arr[i] +                     " " + arr[j] + " " + arr[k]);                 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     console.log("No such triplet exists"); }  // Driver code 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 

Output
numbers are 21 2 19 

Complexity Analysis:

  • Time complexity: O(N^2)
  • Space Complexity: O(1) as no extra space has been used.

Next Article
Find a triplet such that sum of two equals to third element
author
kartik
Improve
Article Tags :
  • Searching
  • JavaScript
  • Web Technologies
  • DSA
  • Arrays
  • Amazon
  • Arcesium
  • two-pointer-algorithm
Practice Tags :
  • Amazon
  • Arcesium
  • Arrays
  • Searching
  • two-pointer-algorithm

Similar Reads

  • 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: arr[] = [1, 2, 3, 4, 5]Output: TrueExplanation: The pair (1, 2) sums to 3. Input: arr[] = [3, 4, 5]Output: TrueExplanation: No triplets satisfy the condition. Input
    14 min read
  • Count triplets such that sum of any two number is equal to third
    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 numb
    7 min read
  • Javascript Program to Find a triplet that sum to a given value
    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. Examples: Input: array = {12, 3, 4, 1, 6, 9}, sum = 24; Output: 12, 3, 9 Explanation: There i
    6 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 < j < k. Examples: Input: arr[] = {1, 2, 3, 4}Output: 1Explanation: O
    6 min read
  • Javascript Program to Find all triplets with zero sum
    Given an array of distinct elements. The task is to find triplets in the array whose sum is zero. Examples : Input : arr[] = {0, -1, 2, -3, 1}Output : (0 -1 1), (2 -3 1)Explanation : The triplets with zero sum are0 + -1 + 1 = 0 and 2 + -3 + 1 = 0 Input : arr[] = {1, -2, 1, 0, 5}Output : 1 -2 1Explan
    6 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. Inpu
    6 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 < b < 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: Amon
    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
    7 min read
  • Javascript Program to Count triplets with sum smaller than a given value
    Given an array of distinct integers and a sum value. Find the count of triplets with a sum smaller than the given sum value. The expected Time Complexity is O(n2). Examples: Input : arr[] = {-2, 0, 1, 3} sum = 2. Output : 2 Explanation : Below are triplets with sum less than 2 (-2, 0, 1) and (-2, 0,
    4 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,
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences