16. 3Sum
mediumAsked at SquarespaceFind every unique triplet that sums to zero; Squarespace uses it to test whether you can combine sorting with the two-pointer pattern and de-duplicate cleanly.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an integer array nums, return all unique triplets [a, b, c] such that a + b + c = 0. The solution set must not contain duplicate triplets.
Constraints
3 <= nums.length <= 3000-10^5 <= nums[i] <= 10^5
Examples
Example 1
nums=[-1,0,1,2,-1,-4][[-1,-1,2],[-1,0,1]]Example 2
nums=[0,1,1][]Approaches
1. Brute force triples
Enumerate every triple and dedupe results via a stringified set.
- Time
- O(n^3)
- Space
- O(n^2)
const seen=new Set(),res=[];
for(let i=0;i<n;i++) for(let j=i+1;j<n;j++) for(let k=j+1;k<n;k++)
if(nums[i]+nums[j]+nums[k]===0){
const t=[nums[i],nums[j],nums[k]].sort((a,b)=>a-b);
const k2=t.join(','); if(!seen.has(k2)){seen.add(k2);res.push(t);}
}
return res;Tradeoff:
2. Sort then two-pointer scan
Sort the array, fix one number, and use two pointers to find the matching pair while skipping duplicates.
- Time
- O(n^2)
- Space
- O(1)
function threeSum(nums) {
nums.sort((a, b) => a - b);
const res = [];
for (let i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] === nums[i - 1]) continue;
let l = i + 1, r = nums.length - 1;
while (l < r) {
const s = nums[i] + nums[l] + nums[r];
if (s === 0) {
res.push([nums[i], nums[l], nums[r]]);
while (l < r && nums[l] === nums[l + 1]) l++;
while (l < r && nums[r] === nums[r - 1]) r--;
l++; r--;
} else if (s < 0) l++; else r--;
}
}
return res;
}Tradeoff:
Squarespace-specific tips
Squarespace evaluators expect the dedupe-skip on the outer and inner pointers and they like a note connecting it to dedupe logic in the media library upload pipeline.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill 3Sum and other Squarespace interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →