Find Triplets with Zero Sum (3Sum Problem)

Find triplets with zero sum (3Sum Problem). Given an array of integers, write a code to find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.

For example –

Example 1:

Input: {-1, 0, 1, 2, -1, -4}

Output: {-1, 0, 1}, {-1, -1, 2}

Example 2:

Input: {-8, -7, 5, 2}

Output: {-7, 5, 2}

This problem is very important in terms of interviews. It is already asked in Amazon, Facebook, Adobe and many other good companies.

In this tutorial, I am going to discuss multiple approaches and their time complexities to solve this problem efficiently.

Method 1: Brute Force Approach

The simplest way to solve 3sum problem is by using a brute force approach. In this approach, we use three for loops to find all unique triplets in the array which gives the sum of zero.

The time complexity of this approach is O(n^3).

Find a peak element in an array

Method 2: Use Sorting

The better way to solve this problem is to first sort the array. Then run two loops to find triplets that sum to zero.

I have also explained this approach using a video tutorial, The link of that video tutorial is mentioned at the end of this post.

The time complexity of this approach is O(n^2).

Find the element that appears once in a sorted array

Find Triplets with Zero Sum (3Sum Problem) – Java Code

Let’s implement the second approach to solve 3 sum problem using java code.

In this approach, to ignore duplicates we have explicitly checked consecutive indices with same value. We can also use HashSet to ignore duplicate values.

Find triplet with given sum in an array

3Sum LeetCode Solution – Java Code

Let’s write a code to find all unique triplets with zero sum using HashSet. We are using HashSet to solve this problem because it does not allow duplicates and it’s lookup time is O(1).

Sorting algorithms and their time complexities

3 Sum Zero InterviewBit Solution – Java Code

We use the similar approach which i have already discussed. First we sort the array and then we run two for loops to find three elements whose sum is equal to zero.

3Sum Solution Java Video Tutorial

In this tutorial, I have explained multiple approaches and it’s time complexities to solve this problem. If you know any other approach to solve this problem efficiently then let us know through your comments.

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.