Example 1
- Input
- nums = [-1,0,1,2,-1,-4]
- Output
- [[-1,-1,2],[-1,0,1]]
The index triplets (0, 1, 2) and (0, 3, 4) give (-1) + 0 + 1 = 0 and (-1) + 2 + (-1) = 0, which are the distinct triplets [-1, 0, 1] and [-1, -1, 2].
Given an integer array nums, return all unique triplets of values that add up to zero, where the three values come from three different positions. No duplicate triplet may appear in the answer.
Given an integer array nums, return all unique triplets [nums[i], nums[j], nums[k]] with three different indices i, j and k such that nums[i] + nums[j] + nums[k] == 0.
The answer must not contain duplicate triplets: two triplets with the same three values in any order count as one, and the triplets may be returned in any order.
3 <= nums.length <= 3000-10^5 <= nums[i] <= 10^5The index triplets (0, 1, 2) and (0, 3, 4) give (-1) + 0 + 1 = 0 and (-1) + 2 + (-1) = 0, which are the distinct triplets [-1, 0, 1] and [-1, -1, 2].
The only triplet available is [0, 1, 1], which sums to 2, so no triplet qualifies.
The single available triplet [0, 0, 0] sums to 0, so it is the whole answer.
Several index choices use the repeated zero and two, but they all give the same value triplet. Return it only once.
The smallest and largest allowed values cancel with zero. Values may be far apart after sorting, so the pair scan starts at both ends.
Three different positions must contribute to a sum of zero, but the answer identifies value combinations rather than positions. Example 1 finds [-1, 0, 1] at more than one index combination, yet it appears only once in the result. Fix one value and search for two others whose sum is its negative. Sorting lets a small pair sum be increased by moving the left pointer and a large pair sum be decreased by moving the right pointer.
Reveal Brute Force: intuition, complexity, and code
[0, 0, 0, 0] produce just [[0, 0, 0]]; three distinct positions can still hold equal values.[-2, 0, 0, 2, 2] produce only [[-2, 0, 2]]. Skipping repeated anchors alone is insufficient.Sorting plus two pointers turns a K-sum search into a fixed-prefix loop around a linear two-sum scan, with duplicate-skipping keeping the output unique.