3Sum
Medium
Topics
Given an integer array nums, return all unique triplets [a, b, c] that sum to 0. The result may be in any order and must not contain duplicate triplets.
Example 1
One answer triplet is shaded: -1 + -1 + 2 = 0. The real work is skipping duplicates, since the answer is a set of triplets, not of index triples.
Cells are the array values; the small numbers underneath are indices.
Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]]
Example 2
Input: nums = [0,0,0] Output: [[0,0,0]]
Constraints
- 3 <= nums.length <= 3000
- -10^5 <= nums[i] <= 10^5
Editorial — intuition, approach, complexity and pitfalls
Intuition
Sort the array; then for each fixed first element, the remaining two-sum-to-target reduces to a two-pointer scan. Sorting also makes it easy to skip duplicates.
Approach
- Sort nums.
- For each index i (skipping duplicate values), two-pointer over the rest looking for sum 0.
- On a hit, record the triplet and advance both pointers past duplicates.
Dry Run
nums = [-1, 0, 1, 2, -1, -4]
sorted -> [-4, -1, -1, 0, 1, 2]
i=0 fix -4, two-pointer over [-1, -1, 0, 1, 2]
L=-1 R=2 sum -3 < 0 move L right
L=-1 R=2 sum -3 < 0 move L right
L= 0 R=2 sum -2 < 0 move L right
L= 1 R=2 sum -1 < 0 move L right, pointers cross
i=1 fix -1, two-pointer over [-1, 0, 1, 2]
L=-1 R=2 sum 0 record [-1, -1, 2]
L= 0 R=1 sum 0 record [-1, 0, 1]
i=2 nums[2] == nums[1] == -1, skip
without this skip, [-1, 0, 1] would be recorded a second time
i=3 fix 0, two-pointer over [1, 2]
L= 1 R=2 sum 3 > 0 move R left, pointers cross
i=4, i=5 fewer than two elements remain
answer [-1, -1, 2] and [-1, 0, 1]
Sorting buys two unrelated things at once. It makes the two-pointer scan valid --
a sum that is too small can only be repaired by moving L right, never R -- and it
puts equal values side by side, which reduces duplicate suppression to a
comparison with the immediate predecessor.
There are two different duplicate skips and both are needed. The outer one at i=2
stops the same first element being fixed twice. The inner ones, after a match,
stop the same pair being recorded twice on input like [0,0,0,0]. On this array the
inner skips never fire -- the two matches land on distinct values -- so the trace
exercises only one of the two.Complexity
- Time — O(n^2): an O(n) two-pointer scan for each of n first elements.
- Space — O(log n) to O(n), and the sort is the only reason: the two-pointer scan itself holds three indices, so O(1). Sorting is not free, though, and "O(1) ignoring the sort" is the answer interviewers push back on.
Arrays.sort(int[])in Java andstd::sortin C++ are in-place quicksort variants that still recurse, so they cost O(log n) of stack; Python'slist.sort()is Timsort, which allocates a merge buffer and costs O(n). The output list is excluded by convention, since it is the answer rather than working memory.
Common Pitfalls
- Skip duplicate values at i and after each match to avoid duplicate triplets.
Full Solution — all languages
class Solution:
def threeSum(self, nums):
nums.sort()
res=[]
n=len(nums)
for i in range(n):
if i>0 and nums[i]==nums[i-1]: continue
left,right=i+1,n-1
while left<right:
s=nums[i]+nums[left]+nums[right]
if s==0:
res.append([nums[i],nums[left],nums[right]]); left+=1; right-=1
while left<right and nums[left]==nums[left-1]: left+=1
while left<right and nums[right]==nums[right+1]: right-=1
elif s<0: left+=1
else: right-=1
return resimport java.util.*;
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res=new ArrayList<>();
int n=nums.length;
for(int i=0;i<n;i++) {
if(i>0&&nums[i]==nums[i-1])continue;
int left=i+1,right=n-1;
while(left<right) {
int s=nums[i]+nums[left]+nums[right];
if(s==0) {
res.add(Arrays.asList(nums[i],nums[left],nums[right]));
left++;
right--;
while(left<right&&nums[left]==nums[left-1])left++;
while(left<right&&nums[right]==nums[right+1])right--;
} else if(s<0)left++;
else right--;
}
}
return res;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<vector<int>> res;
int n=nums.size();
for(int i=0;i<n;i++) {
if(i>0&&nums[i]==nums[i-1])continue;
int left=i+1,right=n-1;
while(left<right) {
int s=nums[i]+nums[left]+nums[right];
if(s==0) {
res.push_back({nums[i],nums[left],nums[right]});
left++;
right--;
while(left<right&&nums[left]==nums[left-1])left++;
while(left<right&&nums[right]==nums[right+1])right--;
} else if(s<0)left++;
else right--;
}
}
return res;
}
};/**
* @param {number[]} nums
* @return {number[][]}
*/ var threeSum = function(nums) {
nums.sort((a,b)=>a-b);
const res=[],n=nums.length;
for(let i=0;i<n;i++) {
if(i>0&&nums[i]===nums[i-1])continue;
let left=i+1,right=n-1;
while(left<right) {
const s=nums[i]+nums[left]+nums[right];
if(s===0) {
res.push([nums[i],nums[left],nums[right]]);
left++;
right--;
while(left<right&&nums[left]===nums[left-1])left++;
while(left<right&&nums[right]===nums[right+1])right--;
} else if(s<0)left++;
else right--;
}
}
return res;
};