noodleProblems/
3Sum
#25

3Sum

AlgorithmmediumArrayTwo PointersSorting

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

The result must not contain duplicate triplets — two triplets are considered the same if they consist of the same three values (regardless of order). You may return the triplets, and the values within each triplet, in any order.

Example cases

  • mixed signs
    in nums = [-1,0,1,2,-1,-4]
    out [[-1,-1,2],[-1,0,1]]
    The distinct triplets summing to 0 are [-1, -1, 2] and [-1, 0, 1].
  • no triplet
    in nums = [0,1,1]
    out []
    No three values sum to 0.
  • all zeros
    in nums = [0,0,0]
    out [[0,0,0]]
    The only triplet is [0, 0, 0].

Constraints

  • 3 <= nums.length <= 3000
  • -10^5 <= nums[i] <= 10^5
Saved
nums =
[-1,0,1,2,-1,-4]