☰ All problems

3Sum

MediumArrayTwo PointersSorting

An auditor scans a ledger of signed amounts, nums, looking for groups of three entries that cancel out exactly. Find every distinct triplet of values [a, b, c] with a + b + c == 0, where the three values sit at three different positions of the array.

Triplets are compared by their values: two triplets made of the same three values, in any order, are the same triplet and must appear only once. Return the triplets in any order, with the values inside each triplet in any order. If nothing cancels out, return an empty list.

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

Explanation: Three groups cancel out: -2 + -1 + 3, -2 + 0 + 2 and -1 + 0 + 1.

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

Explanation: The four possible triplets sum to 4, 13, 10 and 6, never 0.

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

Explanation: Many index choices produce -2, 1, 1, but the triplet is listed once.

Constraints

  • nums has between 3 and 3000 entries.
  • Each entry is an integer from -10^5 to 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