Facebook Pixel3Sum — Coding Practice
3SumMedium

3Sum

Medium 31.2k35% acceptance
ArrayTwo PointersSorting

Given an integer array nums, return all unique triplets [a, b, c] such that a + b + c == 0. No two triplets in the result may be the same set of values.

Deterministic output ordering (required): each triplet must be sorted in ascending order, and the overall list of triplets must be sorted lexicographically (compare the first element, then the second, then the third). Return [] if no triplet sums to zero.

Example 1
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
The two distinct zero-sum triplets, each sorted ascending and the pair ordered lexicographically.
Example 2
Input: nums = [0,1,1]
Output: []
No three values add up to 0.
Example 3
Input: nums = [0,0,0,0]
Output: [[0,0,0]]
Only one unique triplet despite the repeated zeros.
Constraints
  • 3 ≤ nums.length ≤ 3000
  • -10⁵ ≤ nums[i] ≤ 10⁵
Asked atAmazonMetaGoogleApple
JavaScript
Loading editor…
Case 1
[-1,0,1,2,-1,-4]
expected: [[-1,-1,2],[-1,0,1]]
Case 2
[0,1,1]
expected: []
Case 3
[0,0,0,0]
expected: [[0,0,0]]
Case 4
[-2,0,1,1,2]
expected: [[-2,0,2],[-2,1,1]]
Case 5
[3,-2,1,0]
expected: []
Case 6
[-4,-2,-2,-2,0,1,2,2,2,3,3,4,4,6,6]
expected: [[-4,-2,6],[-4,0,4],[-4,1,3],[-4,2,2],[-2,-2,4],[-2,0,2]]