3Sum
Medium · Two pointers
Jump to codeReturn every distinct triplet of values in an integer array that sums to zero. A triplet uses three different indices; duplicate value-triplets should appear once.
Examples
Example 1
nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Example 2
nums = [0,1,1]
Output: []
Constraints
- 3 <= nums.length <= 1000
- -10^5 <= nums[i] <= 10^5
Need a hint?
Fix one value, then solve a sorted two-sum problem.
Asked in real interviews
Candidates reported versions of 3Sum from these company interviews. Some company questions are locked and open with Premium or XP.
Browse all real coding interview questionsSolution approach
Sort the array. For each first position, skip repeated first values, then move left and right pointers through the suffix. Increase left when the sum is too small and decrease right when it is too large. After a match, move both and skip duplicate endpoint values.
Complexity
O(n²) time; sorting space depends on the implementation, plus the result.
Python reference solution
def threeSum(nums):
nums.sort()
answer = []
for i in range(len(nums) - 2):
if i and nums[i] == nums[i - 1]:
continue
left, right = i + 1, len(nums) - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total < 0:
left += 1
elif total > 0:
right -= 1
else:
answer.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
return answer
JavaScript solution
function threeSum(nums) {
nums.sort((a, b) => a - b);
const answer = [];
for (let i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] === nums[i - 1]) continue;
let left = i + 1, right = nums.length - 1;
while (left < right) {
const total = nums[i] + nums[left] + nums[right];
if (total < 0) left++;
else if (total > 0) right--;
else {
answer.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--;
}
}
}
return answer;
}
Java solution
import java.util.*;
class Solution {
public int[][] threeSum(int[] nums) {
Arrays.sort(nums);
List<int[]> answer = new ArrayList<>();
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1, right = nums.length - 1;
while (left < right) {
long total = (long)nums[i] + nums[left] + nums[right];
if (total < 0) left++;
else if (total > 0) right--;
else {
answer.add(new int[]{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--;
}
}
}
return answer.toArray(new int[0][]);
}
}
C++ solution
#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>> answer;
for (int i = 0; i < (int)nums.size() - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1, right = (int)nums.size() - 1;
while (left < right) {
long long total = (long long)nums[i] + nums[left] + nums[right];
if (total < 0) left++;
else if (total > 0) right--;
else {
answer.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--;
}
}
}
return answer;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 9 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
-1,
0,
1,
2,
-1,
-4
]
][
[
-1,
-1,
2
],
[
-1,
0,
1
]
][
[
0,
1,
1
]
][]
[
[
0,
0,
0
]
][
[
0,
0,
0
]
][
[
-2,
0,
1,
1,
2
]
][
[
-2,
0,
2
],
[
-2,
1,
1
]
][
[
-1,
-1,
-1,
2,
2
]
][
[
-1,
-1,
2
]
]Drafts are saved per language in this browser when storage is available.