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 all triplets that sum to a given value or less
Next article icon

Javascript Program to Find a triplet that sum to a given value

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

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 is a triplet (12, 3 and 9) present 
in the array whose sum is 24. 

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.

Method 1:

This is the naive approach to solving the above problem.  

Approach:

A simple method is to generate all possible triplets and compare the sum of every triplet with the given value. The following code implements this simple method using three nested loops.

Algorithm: 

  • Given an array of length n and a sum s
  • Create three nested loop first loop runs from start to end (loop counter i), second loop runs from i+1 to end (loop counter j) and 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 ith, jth and kth element. If the sum is equal to given sum. Print the triplet and break.
  • If there is no triplet, then print that no triplet exist.

Implementation:

JavaScript
// Javascript program to find a triplet // returns true if there is triplet with sum equal  // to 'sum' present in A[]. Also, prints the triplet  function find3Numbers(A, arr_size, sum) {     let l, r;      // Fix the first element as A[i]      for (let i = 0; i < arr_size - 2; i++) {          // Fix the second element as A[j]          for (let j = i + 1; j < arr_size - 1; j++) {              // Now look for the third number              for (let k = j + 1; k < arr_size; k++) {                 if (A[i] + A[j] + A[k] == sum) {                     console.log("Triplet is " + A[i] +                         ", " + A[j] + ", " + A[k]);                     return true;                 }             }         }     }      // If we reach here, then no triplet was found      return false; }  /* Driver code */  let A = [1, 4, 45, 6, 10, 8]; let sum = 22; let arr_size = A.length; find3Numbers(A, arr_size, sum); 

Output
Triplet is 4, 10, 8 

Complexity Analysis: 

  • Time Complexity: O(n3). 
    There are three nested loops traversing the array, so the time complexity is O(n^3)
  • Space Complexity: O(1). 
    As no extra space is required.

Method 2:

This method uses sorting to increase the efficiency of the code. 

Approach:

By Sorting the array the efficiency of the algorithm can be improved. This efficient approach uses the two-pointer technique. Traverse the array and fix the first element of the triplet. Now use the Two Pointers algorithm to find if there is a pair whose sum is equal to x – array[i]. Two pointers algorithm take linear time so it is better than a nested loop.

Algorithm : 

  • Sort the given array.
  • Loop over the array and fix the first element of the possible triplet, arr[i].
  • Then fix two pointers, one at i + 1 and the other at n – 1. And look at the sum, 
  • If the sum is smaller than the required sum, increment the first pointer.
  • Else, If the sum is bigger, Decrease the end pointer to reduce the sum.
  • Else, if the sum of elements at two-pointer is equal to given sum then print the triplet and break.

Implementation:

JavaScript
// Javascript program to find a triplet  // returns true if there is triplet with sum equal // to 'sum' present in A[]. Also, prints the triplet function find3Numbers(A, arr_size, sum) {     let l, r;      /* Sort the elements */     A.sort((a, b) => a - b);      /* Now fix the first element one      by one and find the     other two elements */     for (let i = 0; i < arr_size - 2; i++) {          // To find the other two         // elements, start two index         // variables from two corners of          // the array and move         // them toward each other          // index of the first element in the         l = i + 1;          // remaining elements          // index of the last element         r = arr_size - 1;         while (l < r) {             if (A[i] + A[l] + A[r] == sum) {                 console.log("Triplet is " + A[i] + ", "                     + A[l] + ", " + A[r]);                 return true;             }             else if (A[i] + A[l] + A[r] < sum)                 l++;             else // A[i] + A[l] + A[r] > sum                 r--;         }     }      // If we reach here, then no triplet was found     return false; }  /* Driver program to test above function */  let A = [1, 4, 45, 6, 10, 8]; let sum = 22; let arr_size = A.length;  find3Numbers(A, arr_size, sum); 

Output
Triplet is 4, 8, 10 
  • Complexity Analysis: 
    • Time complexity: O(N^2). 
      There are only two nested loops traversing the array, so time complexity is O(n^2). Two pointers algorithm takes O(n) time and the first element can be fixed using another nested traversal.
    • Space Complexity: O(1). 
      As no extra space is required.

Method 3:

This is a Hashing-based solution. 

Approach:

This approach uses extra space but is simpler than the two-pointers approach. Run two loops outer loop from start to end and inner loop from i+1 to end. Create a hashmap or set to store the elements in between i+1 to j-1. So if the given sum is x, check if there is a number in the set which is equal to x - arr[i] - arr[j]. If yes print the triplet. 

Algorithm: 

  • Traverse the array from start to end. (loop counter i)
  • Create a HashMap or set to store unique pairs.
  • Run another loop from i+1 to end of the array. (loop counter j)
  • If there is an element in the set which is equal to x- arr[i] - arr[j], then print the triplet (arr[i], arr[j], x-arr[i]-arr[j]) and break
  • Insert the jth element in the set.

Implementation:

JavaScript
// JavaScript program to find a triplet using Hashing // returns true if there is triplet // with sum equal to 'sum' present // in A[]. Also, prints the triplet function find3Numbers(A, arr_size, sum) {     // Fix the first element as A[i]     for (let i = 0; i < arr_size - 2; i++) {          // Find pair in subarray A[i+1..n-1]         // with sum equal to sum - A[i]         let s = new Set();         let curr_sum = sum - A[i];         for (let j = i + 1; j < arr_size; j++) {             if (s.has(curr_sum - A[j])) {                 console.log("Triplet is " + A[i] + ", " + A[j] + ", " +                     (curr_sum - A[j]));                 return true;             }             s.add(A[j]);         }     }      // If we reach here, then no triplet was found     return false; }  /* Driver code */ let A = [1, 4, 45, 6, 10, 8];  let sum = 22; let arr_size = A.length; find3Numbers(A, arr_size, sum); 

Output
Triplet is 4, 8, 10 

Complexity Analysis:

  • Time complexity: O(N^2) 
  • Auxiliary Space: O(N)

Please refer complete article on Find a triplet that sum to a given value for more details!


Next Article
Find all triplets that sum to a given value or less
author
kartik
Improve
Article Tags :
  • Sorting
  • JavaScript
  • Web Technologies
  • DSA
  • Arrays
  • Amazon
  • Morgan Stanley
  • Samsung
  • Accolite
  • CarWale
  • two-pointer-algorithm
Practice Tags :
  • Accolite
  • Amazon
  • CarWale
  • Morgan Stanley
  • Samsung
  • Arrays
  • Sorting
  • two-pointer-algorithm

Similar Reads

  • Find all triplets that sum to a given value or less
    Given an array, arr[] and integer X. Find all the possible triplets from an arr[] whose sum is either equal to less than X. Example: Input : arr[] = {-1, 1, 3, 2}, X = 3Output: (-1, 1, 3), (-1, 1, 2)Explanation: If checked manually, the above two are the only triplets from possible 4 triplets whose
    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
  • 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
  • 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, 19Input: {5, 32, 1, 7, 10, 50, 19, 21, 0}Output: no such triplet existQuestion source: Arcesium Interview Experience
    3 min read
  • Javascript Program for Print all triplets in sorted array that form AP
    Given a sorted array of distinct positive integers, print all triplets that form AP (or Arithmetic Progression) Examples : Input : arr[] = { 2, 6, 9, 12, 17, 22, 31, 32, 35, 42 };Output :6 9 122 12 2212 17 222 17 3212 22 329 22 352 22 4222 32 42Input : arr[] = { 3, 5, 6, 7, 8, 10, 12};Output :3 5 75
    4 min read
  • Count triplets with sum smaller than a given value
    Given an array of distinct integers and a sum value. Find count of triplets with sum smaller than 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, 3) Input :
    11 min read
  • Find Maximum value of Increasing Triplet
    Given an array arr[], the task is to return the maximum value of increasing triplet (i, j, k) such that i < j < k and arr[i] < arr[j] < arr[k]. The value of a triplet (i, j, k) is arr[i] - arr[j] + arr[k]. Example: Input: arr = {1, 2, 3,4, 5}Output: 4 Input: arr = {11, 2, 33, 4, 5}Output
    8 min read
  • Find four elements that sum to a given value | Set 3 (Hashmap)
    Given an array of integers, Check if there exist four elements at different indexes in the array whose sum is equal to a given value k. For example, if the given array is {1 5 1 0 6 0} and k = 7, then your function should print "YES" as (1+5+1+0=7). Examples: Input : arr[] = {1 5 1 0 6 0} k = 7 Outp
    7 min read
  • JavaScript Program to Count the Number of Possible Triangles in Array
    Triangles are basic geometric figures with three sides and three angles. Finding the number of triangles that can be created from a given set of side lengths is a frequent challenge in computational programming. In this article, we'll see how to use a JavaScript array to calculate the total number o
    4 min read
  • 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
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