AlgoLounge

3Sum

medium

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] where nums[i] + nums[j] + nums[k] == 0, and the indices i, j and k are all distinct.

The output should not contain any duplicate triplets. You may return the output and the triplets in any order.

Examples

Example 1

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

nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2].

Example 2

Input:  nums = [0,1,1]
Output: []

The only possible triplet does not sum up to 0.

Example 3

Input:  nums = [0,0,0]
Output: [[0,0,0]]

The only possible triplet sums up to 0.

Constraints

  • 3 <= nums.length <= 1000
  • -10⁵ <= nums[i] <= 10⁵
TypeScript
Loading editor…
List of test cases (10)
Case 1
nums = [-1,0,1,2,-1,-4]
Case 2
nums = [0,1,1]
Case 3
nums = [0,0,0]
Case 4
nums = [-2,0,1,1,2]
Case 5
nums = [-4,-1,-1,0,1,2]
Case 6
nums = [1,2,-2,-1]
Case 7
nums = [-1,0,1,2,-1,-4,-2,-3,3,0,4]
Case 8
nums = [0,0,0,0]
Case 9
nums = [-5,-4,-3,-2,-1,0,1,2,3,4,5]
Case 10
nums = [3,0,-2,-1,1,2]