Three Sum

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Write threeSum(nums): return every distinct triple of numbers, taken from three different positions in nums, that adds up to 0. Write each triple in ascending order, list no triple twice, and sort the list by first number, then second, then third. Return [] if there are none. You may reorder nums. For example, threeSum([-1, 0, 1, 2, -1, -4]) is [[-1, -1, 2], [-1, 0, 1]]. The checks include about 3,500 numbers, so trying every triple is too slow.

Your code must pass

  • Finds every triple that adds up to 0
  • Lists each triple once, even with repeated numbers
  • Sorts each triple and the list
  • Returns an empty list when no triple adds up to 0
  • Is fast enough for 3,500 numbers