3 Sum – Finding Triplets with Target Sum in an Array

Finding Triplets 3 Sum – Medium Level Problem

Given an array of integers, nums, find all unique sets of three numbers [nums[i],nums[j],nums[k]] that add up to zero (nums[i]+nums[j]+nums[k]=0).

Make sure each number in a triplet has a different index, and the result should not include duplicate triplets. You can return the triplets in any order.

Three Sum Triplets

Explanation: 

  • nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
  • nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
  • nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
    The distinct triplets are [-1,0,1] and [-1,-1,2].

Explanation: The only possible triplet does not sum up to 0.

Explanation:The only possible triplet sums up to 0.

Constraints:

  • 3 <= nums.length <= 1000
  • -10^5 <= nums[i] <= 10^5

Finding Triplets 3 Sum Solution

Recommendation for Time and Space Complexity – You should aim for a solution with O(n^2) time and O(1) space, where n is the size of the input array.

Hints for solving problems

Hint 1 :

A straightforward solution is to check every possible triplet in the array, resulting in a time complexity of O(n^3). Can you come up with a more efficient approach?

Hint 2 :

Can you think of an algorithm that works after sorting the input array? What insights can we gain by rearranging the equation provided in the problem?

Hint 3 :

By iterating through the array with index i, we can rearrange the equation to -nums[i] = nums[j] + nums[k]. How can we efficiently find the pairs j and k without duplicates?

There are mainly 3 approach to solve this problem-

  1. Brute Force Method
  2. Hash Map Method
  3. Two Pointers Method

1. Brute Force Method

This approach involves checking all possible triplets in the array using three nested loops, leading to a time complexity of O(n³). It’s simple but inefficient for larger datasets.

  • Time complexity: O(n^3)
  • Space complexity: O(m)

where m is the number of triplets and n is the length of the given array.

Code

2. Hash Map Method

By iterating through the array and using a hash map to store previously seen elements, this approach reduces the problem to finding pairs that sum up to a target value. The time complexity is O(n²) due to the nested iteration over the array.

  • Time complexity: O(n^2)
  • Space complexity: O(n)

Code

3. Two Pointers Method

After sorting the array, this method fixes one element and uses two pointers to find pairs that sum to a specific target. It has a time complexity of O(n²) and is more efficient than the brute force method.

  • Time complexity: O(n^2)
  • Space complexity: O(1) or O(n) depending on the sorting algorithm.

Code

More Articles