CodePark/ problems / Three Sum
START PRACTICINGPRACTICE
Coding problem · Data structures and algorithms › Two pointers

Three Sum

mediumabout 25 minutes in an interview

Find every group of three numbers in nums that adds up to 0. Each group is a triplet [a, b, c], and its three values must come from three different positions in the array.

  • Return each triplet only once. Two triplets count as the same when they hold the same three values, wherever those values sit.
  • Order doesn't matter, neither between triplets nor inside one. The tests sort before comparing.
  • If no triplet works, return []. That includes arrays with fewer than 3 numbers.
  • nums holds whole numbers, which can be negative or repeated. It has at most 3,000 of them.
Input: nums = [-3, 1, 2, -2, 0, 1] Output: [[-3, 1, 2], [-2, 0, 2], [-2, 1, 1]]There are two 1s, but -3 + 1 + 2 appears only once.
Input: nums = [0, 0, 0, 0] Output: [[0, 0, 0]]
Input: nums = [1, 2, -4] Output: []