128k views
4 votes
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4],

1 Answer

5 votes

Final answer:

The 3Sum problem is a mathematical problem where we need to find three numbers in an array that sum up to zero. It can be solved using the Two Pointers algorithm.

Step-by-step explanation:

The problem you are describing is known as the 3Sum problem in mathematics and computer science. The goal is to find three numbers in an array that sum up to zero. This problem can be solved using a popular algorithm called the Two Pointers technique. Here's how it works:

  1. Sort the array in ascending order.
  2. Initialize three pointers, i, left, and right. Set i to loop through all array elements from 0 to n-2.
  3. For each i, set left=i+1 and right=n-1.
  4. While left is less than right, check if the sum of array[i] + array[left] + array[right] is equal to zero.
  5. If the sum is zero, add the triplet (array[i], array[left], array[right]) to the result set and increment left and decrement right.
  6. If the sum is less than zero, increment left.
  7. If the sum is greater than zero, decrement right.

This algorithm has a time complexity of O(n^2) and can find all unique triplets that sum up to zero in the given array S = [-1, 0, 1, 2, -1, -4]. The resulting triplets are:

  • [-1, -1, 2]
  • [-1, 0, 1]
User Sottenad
by
8.1k points