3Sum

Medium#15towards each other

You get an array of numbers. Find every triple of numbers from three different places in the array that adds up to 0. Each triple goes into the answer once, even if the array lets you build it in several ways. Our example: [2, -2, 0, 1, -1, -2] — the answer is [-2, 0, 2] and [-1, 0, 1].

input
nums: an array of integers, repeats allowed.
returns
Every triplet [nums[i], nums[j], nums[k]] of three different indices whose numbers add up to 0, each set of three numbers once. Triplets in any order, numbers in a triplet too.
constraints
  • 3 ≤ nums.length ≤ 1000
  • −10⁵ ≤ nums[i] ≤ 10⁵
our 11 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} nums
 * @return {number[][]}
 */
function threeSum(nums) {

}
Ctrl ↵
format
reset

saved in this browser

11 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more two pointers problems

Pattern “Two pointers” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.