Skip to main content

17. 3Sum

mediumAsked at Mercury

Find all unique triplets in an 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. The solution set must not contain duplicate triplets.

Constraints

  • 3 <= nums.length <= 3000
  • -10^5 <= nums[i] <= 10^5

Examples

Example 1

Input
nums = [-1,0,1,2,-1,-4]
Output
[[-1,-1,2],[-1,0,1]]

Example 2

Input
nums = [0,1,1]
Output
[]

Approaches

1. Brute triple loop

Check every (i,j,k) triple and dedupe with a Set of sorted tuples.

Time
O(n^3)
Space
O(n)
const out=new Set();
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) out.add([nums[i],nums[j],nums[k]].sort((a,b)=>a-b).join(','));
return [...out].map(s=>s.split(',').map(Number));

Tradeoff:

2. Sort + two-pointer per anchor

Sort the array, fix each anchor, then close the remaining target with two pointers; skip duplicate anchors and duplicate inner moves.

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 sum = nums[i] + nums[l] + nums[r];
      if (sum < 0) l++;
      else if (sum > 0) r--;
      else {
        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--;
      }
    }
  }
  return res;
}

Tradeoff:

Mercury-specific tips

Mercury reuses two-pointer narrative for reconciling triples of ledger entries — a clearing leg plus its inbound and outbound mirrors should sum to zero in a net-zero internal book.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill 3Sum and other Mercury interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →