Skip to main content

Three Sum

MediumPremium

Given an integer array nums, return all unique triplets [nums[i], nums[j], nums[k]] such that:

  • i != j, i != k, and j != k
  • nums[i] + nums[j] + nums[k] == 0

The solution set must not contain duplicate triplets.

Examples

nums = [-1, 0, 1, 2, -1, -4] output: [[-1, -1, 2], [-1, 0, 1]] explanation: The triplets `[-1, -1, 2]` and `[-1, 0, 1]` are the only unique combinations that sum to zero. nums = [1, 2, -2, -1] output: [] explanation: There are no three numbers in the array that add up to zero. nums = [-2, 0, 1, 1, -2, -1, 0, 2, -1] output: [[-2, 0, 2], [-2, 1, 1], [-1, -1, 2], [-1, 0, 1]] explanation: The array contains four unique triplets that sum to zero.