# Zero-sum triplets challenge

**Problem statement**

Given an array of distinct elements find all triplets in array whose sum is equal to .

**Sample input**

0, -1, 2, -3, 1

**Sample output**

0 -1 1 2 -3 1

**Solution**

We will solve this algorithm in time using hashing. The first iteration will be over all elements of our array. Let that elements be . Then we sum each with a second element (nested loop) and check whether we have a third element that is equal to in our HashSet because would then be equal to . If no such element exists we add the current to the HashSet for future lookups and continue. For each iteration for elements , we generate a new *lookup* HashSet.

**Full Code**

public class FindZeroSumTriplets { private static void pair(int i, int[] a) { int n = a.length; Setset = new HashSet (); for (int j = i + 1; j < n; j++) { if (set.contains(-1 * (a[i] + a[j]))) { System.out.println(" (" + a[i] + ", " + (-1 * (a[i] + a[j])) + ", " + a[j] + ")"); return; } else { set.add(a[j]); } } } private static void solve(int[] a) { int n = a.length; System.out.println("Solving for " + Arrays.toString(a)); for (int i = 0; i < n; i++) { pair(i, a); } System.out.println(); } public static void main(String[] args) { solve(new int[] { 0, -1, 2, -3, 1 }); solve(new int[] { 1, -2, 1, 0, 5 }); solve(new int[] { 0, 0, 0, 0 }); solve(new int[] { -1, 2, -1, 3, -2 }); } }