Magicsheet logo

3Sum

Medium
68.9%
Updated 6/1/2025

3Sum

What is this problem about?

The 3Sum interview question is a classic challenge in array manipulation. You are given an integer array, and your task is to find all unique triplets [nums[i],nums[j],nums[k]][nums[i], nums[j], nums[k]] such that the elements are at different indices and their sum equals exactly zero (nums[i]+nums[j]+nums[k]=0nums[i] + nums[j] + nums[k] = 0). The primary difficulty lies not just in finding the triplets, but in ensuring that the result set contains no duplicate triplets, even if the input array has repeating numbers.

Why is this asked in interviews?

This is a staple 3Sum coding problem for companies like Google, Meta, and Amazon because it tests a candidate’s ability to optimize a brute-force solution. A naive approach using three nested loops results in O(N3)O(N^3) complexity, which is unacceptable for large datasets. This problem evaluates your grasp of sorting, pointers, and duplicate management.

Algorithmic pattern used

The most efficient way to solve this is the Two Pointers interview pattern combined with Sorting. By sorting the array first, you can fix one number and then use two pointers (left and right) to find the remaining two numbers that sum to the negative value of the fixed number. This reduces the complexity to O(N2)O(N^2).

Example explanation

Suppose we have the array: [-1, 0, 1, 2, -1, -4].

  1. Sort the array: [-4, -1, -1, 0, 1, 2].
  2. Fix the first element (e.g., -4). We need the other two to sum to +4. Our pointers at -1 and 2 only sum to 1, so we move on.
  3. Fix the next element: -1. We need the other two to sum to +1.
  • Left pointer at -1, right at 2. Sum is 1. Found: [-1, -1, 2].
  • Left pointer at 0, right at 1. Sum is 1. Found: [-1, 0, 1].
  1. By skipping identical adjacent values, we avoid duplicate triplets like [-1, 0, 1] appearing twice.

Common mistakes candidates make

  • Not handling duplicates: Failing to skip over the same number when moving the fixed index or the pointers, leading to redundant triplets in the output.
  • Poor Time Complexity: Using a Triple-Loop O(N3)O(N^3) approach or using a Hash Set to handle duplicates without sorting, which often leads to high memory overhead.
  • Forgeting to Sort: The two-pointer logic only works if the array is ordered.

Interview preparation tip

Whenever you encounter a "sum" problem involving three or more elements, always ask yourself if sorting the input could simplify the logic. Sorting transforms a chaotic search into a structured traversal where you can predictably move pointers based on whether your current sum is too high or too low.

Similar Questions