Update appNew update is available. Click here to update.
sidenav-btnClose
Topic list
Find All Triplets With Zero Sum
MEDIUM
30 mins
54 upvotes
Sorting
Arrays
Topics (Covered in this problem)
Problem solved
Badge
Skill meter
Sorting
-
-
Arrays
-
-
Other topics
Problem solved
Badge
Skill meter
Strings
-
-
Matrices (2D Arrays)
-
-
Linked List
-
-
Binary Search
-
-
Stacks & Queues
-
-
Trees
-
-
Graph
-
-
Dynamic Programming
-
-
Greedy
-
-
Tries
-
-
SQL
-
-
Binary Search Trees
-
-
Heap
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
userLevel
Sensei
in DSA topics
Open the topic and solve more problems associated with it to improve your skills
Check out the skill meter for every topic
See how many problems you are left with to solve for cracking any stage. Score more than zero to get your progress counted.

Find All Triplets With Zero Sum

Contributed by
Anup Kumar Singh
Medium
yellow-spark
0/80
Avg time to solve 30 mins
Success Rate 50 %
Share
54 upvotes

Problem Statement

You are given an array Arr consisting of n integers, you need to find all the distinct triplets present in the array which adds up to zero.

An array is said to have a triplet {arr[i], arr[j], arr[k]} with 0 sum if there exists three indices i, j and k such that i!=j, j!=k and i!=k and arr[i] + arr[j] + arr[k] = 0.

Note :
1. You can return the list of values in any order. For example, if a valid triplet is {1, 2, -3}, then (2, -3, 1), (-3, 2, 1) etc is also valid triplet. Also, the ordering of different triplets can be random i.e if there are more than one valid triplets, you can return them in any order.
2. The elements in the array need not be distinct.
3. If no such triplet is present in the array, then return an empty list, and the output printed for such a test case will be "-1".
Detailed explanation ( Input/output format, Notes, Constraints, Images )
Sample Input 1 :
 1
 5
-10 5 5 -5 2
 0
Sample Output 1 :
-10 5 5
Explanation for Sample Input 1 :
-10 5 5 is the only triplet that adds up to zero. Note that the order of output does not matter, so 5 -10 5 or 5 5 -10 are also acceptable.
Sample Input 2 :
3
6
1 2 3 -1 -2 -3
0
4
1 2 3 4 
1
6
-1 -1 2 2 -1 -1
0
Sample Output 2 :
1 2 -3
-1 -2 3
-1
-1 -1 2
Explanation for Sample Input 2 :
For the first input (1, 2, -3) and (-1, -2, 3) are the only triplets that add to zero.
In the second input, since there are no such triplets, we print -1.
For the third input, the only distinct triplet is (-1, -1, 2), so just print -1 -1 2.
Reset Code
Full screen
Auto
copy-code
Console