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 Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Javascript Program to Find a triplet such that sum of two equals to third element
Next article icon

Javascript Program to Find all triplets with zero sum

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

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 are
0 + -1 + 1 = 0 and 2 + -3 + 1 = 0

Input : arr[] = {1, -2, 1, 0, 5}
Output : 1 -2 1
Explanation : The triplets with zero sum is
1 + -2 + 1 = 0

Method 1:

This is a simple method that takes O(n3) time to arrive at the result.

Approach:

The naive approach runs three loops and check one by one that sum of three elements is zero or not. If the sum of three elements is zero then print elements otherwise print not found.

Algorithm: 

  • Run three nested loops with loop counter i, j, k
  • The first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet.
  • Check if the sum of elements at i'th, j'th, k'th is equal to zero or not. If yes print the sum else continue.

Below is the implementation of the above approach: 

JavaScript
// A simple Javascript program to find //three elements whose sum is equal to zero arr = [0, -1, 2, -3, 1];  // Prints all triplets in arr[] with 0 sum     function findTriplets(arr) {     let found = false;     for (let i = 0; i < arr.length - 2; i++) {         for (let j = i + 1; j < arr.length - 1; j++) {             for (let k = j + 1; k < arr.length; k++) {                 if (arr[i] + arr[j] + arr[k] === 0) {                     console.log(arr[i] + " " + arr[j] + " " + arr[k]);                     found = true;                 }             }         }         // If no triplet with 0 sum found in array         if (found === false) {             console.log(" not exist ");         }     } } findTriplets(arr); 

Output
0 -1 1 2 -3 1 

Complexity Analysis: 

  • Time Complexity: O(n3). 
    As three nested loops are required, so the time complexity is O(n3).
  • Auxiliary Space: O(1). 
    Since no extra space is required, so the space complexity is constant.

Method 2:

The second method uses the process of Hashing to arrive at the result and is solved at a lesser time of O(n2). 

Approach:

This involves traversing through the array. For every element arr[i], find a pair with sum "-arr[i]". This problem reduces to pair sum and can be solved in O(n) time using hashing.

Algorithm: 

  1. Create a hashmap to store a key-value pair.
  2. Run a nested loop with two loops, the outer loop from 0 to n-2 and the inner loop from i+1 to n-1
  3. Check if the sum of ith and jth element multiplied with -1 is present in the hashmap or not
  4. If the element is present in the hashmap, print the triplet else insert the j'th element in the hashmap.

Below is the implementation of the above approach: 

JavaScript
// Javascript program to find triplets in a given // array whose sum is zero  // function to print triplets with 0 sum function findTriplets(arr, n) {     let found = false;      for (let i = 0; i < n - 1; i++) {         // Find all pairs with sum equals to         // "-arr[i]"         let s = new Set();         for (let j = i + 1; j < n; j++) {             let x = -(arr[i] + arr[j]);             if (s.has(x)) {                 console.log(x + " " + arr[i] + " " + arr[j]);                 found = true;             }             else                 s.add(arr[j]);         }     }      if (found == false)         console.log(" No Triplet Found"); }  // Driver code let arr = [0, -1, 2, -3, 1]; let n = arr.length; findTriplets(arr, n); 

Output
-1 0 1 -3 2 1 

Complexity Analysis: 

  • Time Complexity: O(n2). 
    Since two nested loops are required, so the time complexity is O(n2).
  • Auxiliary Space: O(n). 
    Since a hashmap is required, so the space complexity is linear.

Method 3:

This method uses Sorting to arrive at the correct result and is solved in O(n2) time. 

Approach:

The above method requires extra space. The idea is based on method 2 of this post. For every element check that there is a pair whose sum is equal to the negative value of that element.

Algorithm: 

  1. Sort the array in ascending order.
  2. Traverse the array from start to end.
  3. For every index i, create two variables l = i + 1 and r = n - 1
  4. Run a loop until l is less than r if the sum of array[i], array[l] and array[r] is equal to zero then print the triplet and break the loop
  5. If the sum is less than zero then increment the value of l, by increasing the value of l the sum will increase as the array is sorted, so array[l+1] > array [l]
  6. If the sum is greater than zero then decrement the value of r, by increasing the value of l the sum will decrease as the array is sorted, so array[r-1] < a rray [r].

Below is the implementation of the above approach: 

JavaScript
// Javascript program to find triplets in a given // array whose sum is zero  // function to print triplets with 0 sum function findTriplets(arr, n) {     let found = false;      // sort array elements     arr.sort((a, b) => a - b);      for (let i = 0; i < n - 1; i++) {         // initialize left and right         let l = i + 1;         let r = n - 1;         let x = arr[i];         while (l < r) {             if (x + arr[l] + arr[r] == 0) {                 // print elements if it's sum is zero                 console.log(x + " " + arr[l] + " " + arr[r])                 l++;                 r--;                 found = true;             }              // If sum of three elements is less             // than zero then increment in left             else if (x + arr[l] + arr[r] < 0)                 l++;              // if sum is greater than zero than             // decrement in right side             else                 r--;         }     }      if (found == false)         console.log(" No Triplet Found"); }  // Driven source  let arr = [0, -1, 2, -3, 1]; let n = arr.length; findTriplets(arr, n); 

Output
-3 1 2 -1 0 1 

Complexity Analysis: 

  • Time Complexity : O(n2). 
    Only two nested loops are required, so the time complexity is O(n2).
  • Auxiliary Space : O(1), no extra space is required, so the time complexity is constant.

Please refer complete article on Find all triplets with zero sum for more details!.


Next Article
Javascript Program to Find a triplet such that sum of two equals to third element
author
kartik
Improve
Article Tags :
  • Searching
  • Sorting
  • Hash
  • JavaScript
  • Web Technologies
  • DSA
  • Arrays
  • Google
  • Facebook
  • two-pointer-algorithm
Practice Tags :
  • Facebook
  • Google
  • Arrays
  • Hash
  • Searching
  • Sorting
  • two-pointer-algorithm

Similar Reads

  • 3 Sum - Find All Triplets with Zero Sum
    Given an array arr[], the task is to find all possible indices {i, j, k} of triplet {arr[i], arr[j], arr[k]} such that their sum is equal to zero and all indices in a triplet should be distinct (i != j, j != k, k != i). We need to return indices of a triplet in sorted order, i.e., i < j < k. E
    11 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
  • 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 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
  • 3 Sum - Find Unique Triplets with Zero Sum
    Given an array arr[], the task is to find all unique triplets {arr[i], arr[j], arr[k]} such that their sum is equal to zero. Note: All indices in a triplet should be distinct (i != j, j != k, k != i).Each triplet should be sorted, i.e., arr[i] <= arr[j] <= arr[k].Examples: Input: arr[] = {0, -
    15+ min read
  • 3 Sum - Find all Triplets with Given Sum
    Given an array arr[] and an integer target, the task is to find all possible indices {i, j, k} of triplet {arr[i], arr[j], arr[k]} such that their sum is equal to given target and all indices in a triplet should be distinct (i != j, j != k, k != i). We need to return indices of a triplet in sorted o
    12 min read
  • Javascript Program for Number of unique triplets whose XOR is zero
    Given N numbers with no duplicates, count the number of unique triplets (ai, aj, ak) such that their XOR is 0. A triplet is said to be unique if all of the three numbers in the triplet are unique. Examples: Input : a[] = {1, 3, 5, 10, 14, 15};Output : 2 Explanation : {1, 14, 15} and {5, 10, 15} are
    3 min read
  • Count triples with Bitwise AND equal to Zero
    Given an array of integers A[] consisting of N integers, find the number of triples of indices (i, j, k) such that A[i] & A[j] & A[k] is 0(<0 ? i, j, k ? N and & denotes Bitwise AND operator. Examples: Input: A[]={2, 1, 3}Output: 12Explanation: The following i, j, k triples can be cho
    7 min read
  • 2 Sum - Find All Pairs With Zero Sum
    Given an array arr[], the task is to find all possible indices (i, j) of pairs (arr[i], arr[j]) whose sum is equal to 0 and i != j. We can return pairs in any order, but all the returned pairs should be internally sorted, that is for any pair(i, j), i should be less than j. Examples: Input: arr[] =
    9 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
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