3Sum
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Given an integer array nums, return every unique triplet [nums[i], nums[j], nums[k]] of three different positions whose values add up to 0.
Understand the problem
- A triplet is a group of three numbers.
- You need three different positions (
i,j,kall different), whose values sum to exactly0. For example-1 + 0 + 1 = 0. - Unique means the same group of values must not appear twice in your answer.
[-1, 0, 1]and[0, 1, -1]are the same triplet (same values, different order), so only one of them may appear. - Return the triplets in any order, with the numbers inside each triplet in any order.
Example 1
Input: nums = [-1, 0, 1, 2, -1, -4]
Output: [[-1, -1, 2], [-1, 0, 1]]-1 + -1 + 2 = 0(using both-1s, which sit at different positions).-1 + 0 + 1 = 0. There are two-1s, so this triplet can be built two ways, but it's listed only once.
Example 2
Input: nums = [0, 1, 1]
Output: []The only triplet is 0 + 1 + 1 = 2, not 0.
Example 3
Input: nums = [0, 0, 0, 0]
Output: [[0, 0, 0]]Many ways to pick three zeros, but they all give the same triplet.
Constraints
3 <= nums.length <= 3000-10^5 <= nums[i] <= 10^5
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Sort the array, fix the first number of the triplet, and find the other two with two pointers moving inward from both ends of what's left.
The naive approach (and why it's slow)
Try every combination of three positions with three nested loops. That's about n³ / 6 triplets: for 3,000 numbers, around 4.5 billion. On top of that, you'd need a set to filter out duplicate triplets. This is O(n³), far too slow.
The key insight
Step 1: three becomes two. If the first number is nums[i], the other two must add up to -nums[i]. So for each i, we're solving Two Sum on the rest of the array.
Step 2: sorted Two Sum is easy with two pointers. In a sorted range, put left at the smallest value and right at the largest:
- Sum too small? The only way to make it bigger is to move
leftright (to a bigger number). - Sum too big? The only way to make it smaller is to move
rightleft. - Each step throws away one number for good, so one pass over the range is enough.
Step 3: sorting also fixes duplicates. Equal values end up next to each other, so we can simply skip a value we just used.
Step by step
nums = [-1, 0, 1, 2, -1, -4] → sorted: [-4, -1, -1, 0, 1, 2] (indices 0 to 5).
i = 0, first number -4, need the other two to sum to 4:
left | right | Sum of three | Action |
|---|---|---|---|
-1 | 2 | -4 + -1 + 2 = -3 | too small → left++ |
-1 | 2 | -3 | too small → left++ |
0 | 2 | -2 | too small → left++ |
1 | 2 | -1 | too small → left++ |
Pointers met, no triplet starts with -4.
i = 1, first number -1, need the other two to sum to 1:
left | right | Sum of three | Action |
|---|---|---|---|
-1 | 2 | -1 + -1 + 2 = 0 | ✅ record [-1, -1, 2], move both |
0 | 1 | -1 + 0 + 1 = 0 | ✅ record [-1, 0, 1], move both |
Pointers met.
i = 2, first number -1 again: same value as i = 1, so skip it. Any triplet starting with it was already found.
i = 3, first number 0: only 1 and 2 are left, sum 3, no match. After that, the first number would be positive, and three positives can't sum to 0, so we stop.
Answer: [[-1, -1, 2], [-1, 0, 1]].
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Time: O(n²). Sorting is O(n log n). Then for each of the
nfirst numbers, the two pointers make one O(n) pass.n × nwins. - Memory: O(1) besides the output (sorting may use some memory, depending on the language).
Common mistakes
- Forgetting to sort. The two-pointer moves only make sense in a sorted array.
- Not skipping duplicates of the first number. With
[-1, -1, 0, 1]you'd record[-1, 0, 1]twice. - Not skipping duplicates after a match. After recording a triplet, move
leftpast every copy of the same value, or you'll record the same triplet again. - Using a set of triplets to de-duplicate. It works, but it's slower and messier than skipping in the sorted array.
Going deeper
- Stopping early once
nums[i] > 0is a nice touch: everything after it is positive too. - The same "fix one, two pointers for the rest" idea extends to 4Sum (fix two, O(n³)) and 3Sum Closest.
Reference solution
/**
* @param {number[]} nums
* @return {number[][]}
*/
export default function threeSum(nums) {
// Sorting makes the two-pointer moves work, and puts duplicates side by side.
const sorted = [...nums].sort((a, b) => a - b)
const result = []
// sorted[i] is the first number. Once it's positive, three positives can't sum to 0.
for (let i = 0; i < sorted.length - 2 && sorted[i] <= 0; i++) {
// Same first number as last time: every triplet it makes was already found.
if (i > 0 && sorted[i] === sorted[i - 1]) continue
// Two Sum on the sorted range after i, with pointers at both ends.
let left = i + 1
let right = sorted.length - 1
while (left < right) {
const sum = sorted[i] + sorted[left] + sorted[right]
if (sum < 0)
left++ // too small: move to a bigger number
else if (sum > 0)
right-- // too big: move to a smaller number
else {
result.push([sorted[i], sorted[left], sorted[right]])
left++
right--
// Skip copies of the value we just used, so this triplet isn't recorded again.
while (left < right && sorted[left] === sorted[left - 1]) left++
}
}
}
return result
}export default function threeSum(nums: number[]): number[][] {
// Sorting makes the two-pointer moves work, and puts duplicates side by side.
const sorted = [...nums].sort((a, b) => a - b)
const result: number[][] = []
// sorted[i] is the first number. Once it's positive, three positives can't sum to 0.
for (let i = 0; i < sorted.length - 2 && sorted[i] <= 0; i++) {
// Same first number as last time: every triplet it makes was already found.
if (i > 0 && sorted[i] === sorted[i - 1]) continue
// Two Sum on the sorted range after i, with pointers at both ends.
let left = i + 1
let right = sorted.length - 1
while (left < right) {
const sum = sorted[i] + sorted[left] + sorted[right]
if (sum < 0)
left++ // too small: move to a bigger number
else if (sum > 0)
right-- // too big: move to a smaller number
else {
result.push([sorted[i], sorted[left], sorted[right]])
left++
right--
// Skip copies of the value we just used, so this triplet isn't recorded again.
while (left < right && sorted[left] === sorted[left - 1]) left++
}
}
}
return result
}def three_sum(nums: list[int]) -> list[list[int]]:
# Sorting makes the two-pointer moves work, and puts duplicates side by side.
nums = sorted(nums)
result = []
for i in range(len(nums) - 2):
# nums[i] is the first number. Once it's positive, three positives can't sum to 0.
if nums[i] > 0:
break
# Same first number as last time: every triplet it makes was already found.
if i > 0 and nums[i] == nums[i - 1]:
continue
# Two Sum on the sorted range after i, with pointers at both ends.
left, right = i + 1, len(nums) - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total < 0:
left += 1 # too small: move to a bigger number
elif total > 0:
right -= 1 # too big: move to a smaller number
else:
result.append([nums[i], nums[left], nums[right]])
left += 1
right -= 1
# Skip copies of the value we just used, so this triplet isn't recorded again.
while left < right and nums[left] == nums[left - 1]:
left += 1
return result