1. Sort + Two-Sum Hash Set Lookup
After sorting to skip duplicate pivots, run a O(n) Hash Set complement lookup inside the outer loop to find pairs summing to -nums[i].
N outer pivots each perform an O(n) hash-set inner pass.
Allocates a Hash Set of up to n elements per outer step.
How It Works
Reducing 3Sum to Repeated Two-Sum Lookups
If you replace the two converging pointers with a Hash Set complement scan for each outer index i:
- Sort
nums(still crucial so duplicate outernums[i]values can be skipped cleanly). - For each
iwithnums[i] <= 0:
- Initialize an empty
seenset. - Loop
jfromi + 1ton - 1: computecomplement = -nums[i] - nums[j]. - If
complementis inseen, emit[nums[i], complement, nums[j]]and advancejpast duplicates so the pair isn't emitted twice. - Add
nums[j]intoseen.
While still O(n²) time, this allocates O(n) hash-set memory compared to Two Pointers' O(1) auxiliary work.
Step-by-Step Dry Run
Scan suffix [-1, 0, 1, 2] with seen = {}. complement for -1 is 2 (not seen yet); insert -1.
seen = {-1}- +Connects 3Sum directly to classic 2Sum complement lookup
- -Uses O(n) hash-set heap allocations per outer loop; slower constant factors than Two Pointers
Reference Implementation
Complete implementation for Sort + Two-Sum Hash Set Lookup in Python, JavaScript, Java, C++, and C.
def three_sum_hash(nums: list[int]) -> list[list[int]]:nums.sort()res = []n = len(nums)for i in range(n - 2):if nums[i] > 0:breakif i > 0 and nums[i] == nums[i - 1]:continueseen = set()j = i + 1while j < n:comp = -nums[i] - nums[j]if comp in seen:res.append([nums[i], comp, nums[j]])while j + 1 < n and nums[j] == nums[j + 1]:j += 1seen.add(nums[j])j += 1return res
function threeSumHash(nums) {
nums.sort((a, b) => a - b);
const res = [];
for (let i = 0; i < nums.length - 2; i++) {
if (nums[i] > 0) break;
if (i > 0 && nums[i] === nums[i - 1]) continue;
const seen = new Set();
for (let j = i + 1; j < nums.length; j++) {
const comp = -nums[i] - nums[j];
if (seen.has(comp)) {
res.push([nums[i], comp, nums[j]]);
while (j + 1 < nums.length && nums[j] === nums[j + 1]) j++;
}
seen.add(nums[j]);
}
}
return res;
}import java.util.*;
public class Solution {
public static List<List<Integer>> threeSumHash(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < nums.length - 2; i++) {
if (nums[i] > 0) break;
if (i > 0 && nums[i] == nums[i - 1]) continue;
Set<Integer> seen = new HashSet<>();
for (int j = i + 1; j < nums.length; j++) {
int comp = -nums[i] - nums[j];
if (seen.contains(comp)) {
res.add(Arrays.asList(nums[i], comp, nums[j]));
while (j + 1 < nums.length && nums[j] == nums[j + 1]) j++;
}
seen.add(nums[j]);
}
}
return res;
}
}#include <vector>
#include <unordered_set>
#include <algorithm>
std::vector<std::vector<int>> threeSumHash(std::vector<int>& nums) {
std::sort(nums.begin(), nums.end());
std::vector<std::vector<int>> res;
int n = static_cast<int>(nums.size());
for (int i = 0; i < n - 2; i++) {
if (nums[i] > 0) break;
if (i > 0 && nums[i] == nums[i - 1]) continue;
std::unordered_set<int> seen;
for (int j = i + 1; j < n; j++) {
int comp = -nums[i] - nums[j];
if (seen.count(comp)) {
res.push_back({nums[i], comp, nums[j]});
while (j + 1 < n && nums[j] == nums[j + 1]) j++;
}
seen.insert(nums[j]);
}
}
return res;
}#include <stdbool.h>
#include <stdlib.h>
static int cmpInt3(const void* a, const void* b) {
int x = *(const int*)a, y = *(const int*)b;
return (x > y) - (x < y);
}
static bool hasValueInRange(const int* nums, int l, int r, int target) {
while (l <= r) {
int m = l + (r - l) / 2;
if (nums[m] == target) return true;
if (nums[m] < target) l = m + 1;
else r = m - 1;
}
return false;
}
int** threeSumBinaryLookup(int* nums, int n, int* returnSize, int** returnColSizes) {
qsort(nums, n, sizeof(int), cmpInt3);
int cap = 128;
int** res = (int**)malloc(cap * sizeof(int*));
*returnColSizes = (int*)malloc(cap * sizeof(int));
*returnSize = 0;
for (int i = 0; i < n - 2; i++) {
if (nums[i] > 0) break;
if (i > 0 && nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j < n - 1; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
int need = -nums[i] - nums[j];
if (hasValueInRange(nums, j + 1, n - 1, need)) {
res[*returnSize] = (int*)malloc(3 * sizeof(int));
res[*returnSize][0] = nums[i];
res[*returnSize][1] = nums[j];
res[*returnSize][2] = need;
(*returnColSizes)[*returnSize] = 3;
(*returnSize)++;
}
}
}
return res;
}