AlgoMaster Logo

3Sum

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

The simplest approach is to try every possible triplet in the array and check if their sum is zero. Although this guarantees we find all solutions, it is not efficient.

Intuition:

  1. We iterate through each element, and for each element, iterate over every pair of subsequent elements.
  2. We check if the sum of these three elements is zero.
  3. If the sum is zero, we add the triplet to our list of solutions.
  4. To ensure we do not add duplicate triplets, we use a set to store the triplets.

Code:

2. Two Pointers

The two-pointers approach is more efficient. By sorting the array and using two pointers, we reduce the time complexity significantly.

Intuition:

  1. First, sort the array. This helps in avoiding duplicates and allows the use of two pointers.
  2. Iterate through the sorted array with an index i.
  3. For each i, initialize two pointers: left at i+1 and right at the end of the array.
  4. Calculate the sum of the elements at ileft, and right.
  5. If the sum is zero, add the triplet to the results and move both pointers inward, skipping duplicates.
  6. If the sum is less than zero, move the left pointer to increase the sum.
  7. If the sum is greater than zero, move the right pointer to decrease the sum.

Code: