3Sum

medium

Given an integer array nums, find all unique triplets [nums[i], nums[j], nums[k]] — where i, j, and k are three different indices — whose values add up to 0.

Two triplets count as the same if they hold the same three values, so your answer must not contain any triplet twice. The order of the triplets, and the order of the numbers inside each triplet, does not matter.

Hints

You're really hunting for three numbers that cancel out to zero. What if you locked one of them in place first?
Once one number is fixed at value x, the other two must sum to -x — that's the classic Two Sum problem.
Sort the array first. Then for each anchor, walk one pointer in from the left and one from the right, squeezing toward the target.

Common doubts

Sorting lets us skip duplicate values in O(1) and enables the two-pointer squeeze. Without it, deduplicating triplets is far messier.
Skip an anchor when it equals the previous one, and after finding a match, advance both pointers past any repeated values. That guarantees each distinct triplet is emitted exactly once.
No. The judge normalizes each triplet and the overall list, so [-1, 0, 1] and [0, -1, 1] are treated as identical.

Interview follow-ups

Same template — the pair now needs to sum to target - nums[i] rather than -nums[i].
Add one more outer loop to fix two anchors, then two-pointer the remaining pair for O(n³). The idea generalizes to kSum via recursion.
No meaningfully better general algorithm is known; 3SUM is conjectured to be essentially quadratic, which is why a whole class of problems reduces to it.

Fun facts

  • 3SUM is so fundamental that an entire complexity class — '3SUM-hard' problems — is defined by reductions to it, especially in computational geometry.
  • The two-pointer squeeze reappears in Container With Most Water, Trapping Rain Water, and 4Sum.

Asked at

AmazonFacebookGoogleMicrosoftAdobeAppleBloomberg
Frequently Sometimes Occasionally
Example 1
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
(-1) + 0 + 1 = 0 and (-1) + (-1) + 2 = 0. The two distinct triplets are [-1,0,1] and [-1,-1,2]; order does not matter.
Example 2
Input: nums = [0,1,1]
Output: []
The only possible triplet, 0 + 1 + 1, does not sum to 0.
Example 3
Input: nums = [0,0,0]
Output: [[0,0,0]]
0 + 0 + 0 = 0, giving the single triplet [0,0,0].
Constraints

- 3 <= nums.length <= 3000 - -10^5 <= nums[i] <= 10^5

Solve this problem →