16. 3Sum
mediumAsked at CoupangFind all unique triplets that sum to zero, mirroring how Coupang's bundle-pricing engine identifies SKU combinations that hit a target promotional discount during peak-event throughput.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an 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 triple loop
Try all i<j<k and dedupe.
- Time
- O(n^3)
- Space
- O(n)
for i, for j>i, for k>j: if sum===0 push sorted triplet to a Set keyed by tuple;Tradeoff:
2. Sort + two pointers
Sort, fix one element, then two-pointer scan for the remaining pair sum. Skip duplicates as you go.
- Time
- O(n^2)
- Space
- O(1) extra
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 l = i + 1, r = nums.length - 1;
while (l < r) {
const s = nums[i] + nums[l] + nums[r];
if (s === 0) {
out.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 out;
}Tradeoff:
Coupang-specific tips
Coupang's bundle-pricing engine identifies SKU combinations that hit a target promotional discount during peak-event throughput; the sort + two-pointer pattern is the standard for combinatorial pricing checks at sub-quadratic cost.
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 Coupang interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →