Skip to main content

20. 3Sum

mediumAsked at Udemy

Find all unique triplets that sum to zero — Udemy uses this to test deduplication logic relevant to course bundle pricing and recommendation filtering.

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

Problem

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i, j, k are distinct and nums[i] + nums[j] + nums[k] == 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. Brute force

Try every triple with three nested loops; use a Set to deduplicate — O(n^3).

Time
O(n^3)
Space
O(n)
// three nested loops + deduplication via sorted key in Set
// correct but too slow for n=3000

Tradeoff:

2. Sort + two pointers

Sort the array; for each index i fix nums[i] as the first element and use a left/right pointer pair to find complementary pairs; skip duplicates at both the outer and inner loop levels.

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) {
        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 (sum < 0) l++;
      else r--;
    }
  }
  return res;
}

Tradeoff:

Udemy-specific tips

Udemy asks about e-learning recommendation systems, content search, and marketplace algorithms — balanced mix of arrays, hash maps, and dynamic programming problems.

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

Practice these live with InterviewChamp.AI →