14. 3Sum
mediumAsked at PostmanFind all unique triplets in the array that sum to zero.
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 and the indices are distinct. The result 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,0,0][[0,0,0]]Approaches
1. Triple loop
Enumerate every triple and use a Set of sorted-string keys to dedupe.
- Time
- O(n^3)
- Space
- O(n^2)
// nested i,j,k; if sum==0 add JSON.stringify([a,b,c].sort()) to setTradeoff:
2. Sort + two-pointer
Sort the array; for each fixed i, walk lo and hi pointers inward, skipping duplicates on all three positions.
- Time
- O(n^2)
- Space
- O(1)
function threeSum(nums) {
nums.sort((a,b)=>a-b);
const out = [];
for (let i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] === nums[i-1]) continue;
let lo = i+1, hi = nums.length - 1;
while (lo < hi) {
const s = nums[i] + nums[lo] + nums[hi];
if (s === 0) {
out.push([nums[i], nums[lo], nums[hi]]);
while (lo < hi && nums[lo] === nums[lo+1]) lo++;
while (lo < hi && nums[hi] === nums[hi-1]) hi--;
lo++; hi--;
} else if (s < 0) lo++;
else hi--;
}
}
return out;
}Tradeoff:
Postman-specific tips
Postman expects the dedupe-skip pattern verbalized — it's the same shape as deduping repeated headers in a request before signing it.
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 Postman interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →