☰ All problems

16. 3Sum

MediumArrayTwo PointersSorting

Given an integer array nums, return every distinct triplet of values [a, b, c] taken from three different positions i, j, k of the array such that a + b + c == 0.

Two triplets are the same if they contain the same values, so the result must not contain duplicates. The triplets may be returned in any order, and so may the values inside each triplet.

Example 1
Input: nums = [-2,0,1,1,2,-1]
Output: [[-2,0,2],[-2,1,1],[-1,0,1]]

Explanation: -2 + 1 + 1 = 0 uses both 1s. [-1,0,1] can be built with either of the two 1s, but it is listed only once.

Example 2
Input: nums = [3,-1,5]
Output: []

Explanation: The only triplet sums to 7.

Example 3
Input: nums = [0,0,0,0]
Output: [[0,0,0]]

Explanation: Several index choices give [0,0,0], but it is reported once.

Constraints

  • 3 <= nums.length <= 3000
  • -10^5 <= nums[i] <= 10^5
💡 Hint 1

Checking every triple is O(n³). If you fix the first value a, what problem is left for the other two?

💡 Hint 2

After sorting, "find two values summing to -a" can be solved with two pointers moving towards each other.

💡 Hint 3

To avoid duplicate triplets, skip over equal neighbours: for the fixed value and for each pointer after a match.

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
function threeSum(nums) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc