3Sum

MediumTwo pointers

Given an array of integers nums, return every triplet of values that adds up to zero, where the three values come from three different positions.

Each triplet should appear once: [-1, 0, 1] and [0, 1, -1] are the same triplet. The triplets, and the numbers inside each, can be in any order.

Examples

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

-2 + 0 + 2 and -2 + 1 + 1 are both zero.

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

No three of them add up to zero.

Constraints

  • 3 ≤ nums.length ≤ 3000
  • -10⁵ ≤ nums[i] ≤ 10⁵

Stuck?

Hint 1

Sort the array first. Then fix the first number and look for two more that add up to its negative.

Hint 2

In the sorted rest, move a left and a right pointer toward each other, and skip values you have just used so no triplet repeats.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 9 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur