Skip to main content

14. 3Sum

mediumAsked at ByteDance

Return all unique triplets summing to zero — ByteDance uses it to test sort + two-pointer scaffolding and de-duplication discipline.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given an integer array nums, return every unique triplet [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,0,0]
Output
[[0,0,0]]

Approaches

1. Triple loop with set dedup

Try every triple, sort each tuple, and dedup with a string set.

Time
O(n^3)
Space
O(n^2)
// nested loops -> push sorted triples into a Set keyed by JSON

Tradeoff:

2. Sort then two-pointer scan

Sort the array, fix one anchor, then two-pointer scan the rest. Skip equal neighbors to avoid duplicate triplets.

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:

ByteDance-specific tips

ByteDance interviewers grade hard on the dedup skip lines — sloppy skips become bugs in their content-fingerprint pipeline, so they want them explicitly named.

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 ByteDance interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →