13. 3Sum

Return every unique triplet [a, b, c] from nums (three different positions) with a + b + c = 0. The output must not contain duplicate triplets; any order is fine.

Example 1

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

Example 2

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

Constraints

  • 3 ≤ nums.length ≤ 3000
Hint 1

Sort first. Fix the first number, then the problem becomes Two Sum II on the rest.

Hint 2

Skip equal neighbours to avoid duplicate triplets.

Two PointersSorting