Skip to content

Commit 7b965cc

Browse files
Create Readme.md
1 parent cc1c942 commit 7b965cc

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

Triplets with zero sum/Readme.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
Problem : **Given an array of distinct elements. The task is to find triplets in the array whose sum is zero.**
2+
3+
Method : This method uses Sorting to arrive at the correct result and is solved in O(n^2) time.
4+
5+
Approach:
6+
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.
7+
Algorithm:
8+
1. Sort the array in ascending order.
9+
2. Traverse the array from start to end.
10+
3. For every index i, create two variables l = i + 1 and r = n – 1
11+
4. Run a loop until l is less than r, if the sum of array[l], array[r] is equal to zero then print the triplet and break the loop
12+
5. If the sum is less than zero then increment value of l, by increasing value of l the sum will increase as the array is sorted, so array[l+1] > array [l]
13+
6. If the sum is greater than zero then decrement value of r, by increasing value of l the sum will decrease as the array is sorted, so array[r-1] < array [r].

0 commit comments

Comments
 (0)