MediumArrayTwo PointersSortingUpdated Sep 2026

15. 3Sum

Asked at Google, Meta, Amazon, Apple and 5 more

Difficulty

Medium

Time

O(n^2)

Space

O(1)

Pattern

Array

Companies

9

Problem

You are given an integer array nums. Find every group of three different positions i, j, k where the three values add up to zero: nums[i] + nums[j] + nums[k] == 0.

Return a list of those triplets. The same triplet must appear only once in the answer, even if the array contains the same numbers in several places. For example, if the array has two -1 values, the triplet [-1, 0, 1] should still be listed once.

The order of the triplets in your answer does not matter, and the order of the three numbers inside a triplet does not matter either.

Find groups of three that add to zero

sorted nums-1 + 0 + 1 = 0-4-1-1012012345One valid group is the values at indices 1, 3 and 4.sorted nums-1 + -1 + 2 = 0-4-1-1012012345A second valid group uses both copies of -1 togetherwith 2.
From the sorted array we need every distinct group of three values whose sum is 0.

Constraints

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

Examples

Example 1
Inputnums = [-1,0,1,2,-1,-4]
Output[[-1,-1,2],[-1,0,1]]
WhyThe values -1, 0 and 1 add to 0, and so do -1, -1 and 2. Even though the array holds two copies of -1, each of these triplets is reported only once.
Example 2
Inputnums = [0,1,1]
Output[]
WhyThe only possible choice is 0 + 1 + 1 = 2, which is not zero, so there is no answer.
Example 3
Inputnums = [0,0,0]
Output[[0,0,0]]
WhyAll three values are zero and they add to zero. It is one triplet, not several, because the positions are used only once.

Asked At

9 companies

How to Think About It

1

Brute force: three nested loops checking every triplet. That's O(n³) — n³/6 triplets to check. Way too slow.

2

Key insight: sort the array first. Then for each element nums[i], use two pointers (left and right) to find pairs that sum to -nums[i]. This reduces the inner search from O(n²) to O(n).

3

Why sorting helps: with a sorted array, if the sum is too small, move left right (increases sum). If too large, move right left (decreases sum). This eliminates half the search space at each step.

4

The main pitfall is duplicates. You must skip duplicate values at three places: (1) skip duplicate nums[i] values, (2) skip duplicate left values after finding a triplet, (3) skip duplicate right values after finding a triplet.

5

Edge cases: fewer than 3 elements (return empty), all zeros (return one triplet [0,0,0]), no valid triplets (return empty).

Optimal Approach

Step 1: Sort the array.
Step 2: For each index i (skip duplicates):
- Set left = i+1, right = n-1
- Calculate sum = nums[i] + nums[left] + nums[right]
- If sum == 0: record triplet, skip duplicates on both sides, move both pointers
- If sum < 0: move left right (need larger sum)
- If sum > 0: move right left (need smaller sum)

The duplicate skip at nums[i] is critical. Without it, you'd record the same triplet multiple times.

Time: O(n²) — outer loop O(n), inner two-pointer scan O(n). Space: O(1) excluding output.

Fix one value, then use two pointers

sorted nums-4-1-1012012345lohii = 0 holds -4, so we need lo + hi = 4. Start with loat 1 and hi at 5.sorted nums-1 + 2 = 1-4-1-1012012345lohii = 1 holds -1, so we need lo + hi = 1. The pair -1and 2 hits it exactly.sorted nums0 + 1 = 1-4-1-1012012345lohiAfter recording a triplet, skip equal neighbours andmove both pointers inward to find the next pair.sort firstif sum < 0: lo++if sum > 0: hi--if sum == 0: record and skip duplicates
After sorting, each fixed value i is matched with a left and right pointer that walk toward each other.
ComplexityTime O(n^2)Space O(1)The sort costs O(n log n), then the outer loop runs n times and each inner two-pointer scan moves across the array once, giving O(n^2); only a few index variables are stored, not counting the output.

What Trips People Up in Real Interviews

1

Forgetting to sort first. Without sorting, you can't use the two-pointer technique. Sorting is O(n log n) and is the prerequisite for the O(n²) solution.

2

Skipping duplicate elements incorrectly. After finding a valid triplet, skip all duplicate values to avoid duplicate triplets. But don't skip the first occurrence — you need it.

3

Confusing "return all unique triplets" with "return all triplets." If the input has duplicates like [-1, -1, 2], you should only return [-1, -1, 2] once, not twice.

4

Not handling the case where no triplet exists. Return an empty list, not null or an error.

5

Off-by-one in the outer loop: using range(len(nums)) instead of range(len(nums) - 2). The last two elements can't be the first element of a triplet since you need at least two elements after them.

Solution Code

O(n^2) time
def threeSum(nums):
    nums.sort()
    result = []
    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        lo, hi = i + 1, len(nums) - 1
        while lo < hi:
            total = nums[i] + nums[lo] + nums[hi]
            if total < 0:
                lo += 1
            elif total > 0:
                hi -= 1
            else:
                result.append([nums[i], nums[lo], nums[hi]])
                while lo < hi and nums[lo] == nums[lo + 1]:
                    lo += 1
                while lo < hi and nums[hi] == nums[hi - 1]:
                    hi -= 1
                lo += 1
                hi -= 1
    return result

Pro at DSA?

Test your skills with a real FAANG-style mock interview.

Start a Mock Interview →

Frequently Asked Questions

What is the 3Sum problem?

Given an array of integers, find all unique triplets that sum to zero. This problem extends Two Sum into three dimensions and tests your ability to handle duplicates and optimize with two pointers.

How do you solve 3Sum?

The optimal approach runs in O(n^2) time and O(1) space. Scroll up to "Optimal Approach" for the step-by-step walkthrough, diagrams, and code in Python, C++ and Java.

What companies ask 3Sum?

3Sum is asked at Google, Meta, Amazon, Apple, Microsoft, Oracle, Salesforce, Walmart, Bloomberg. It is a medium difficulty problem.

What are common mistakes on 3Sum?
  • Forgetting to sort first. Without sorting, you can't use the two-pointer technique. Sorting is `O(n log n)` and is the prerequisite for the `O(n²)` solution.
  • Skipping duplicate elements incorrectly. After finding a valid triplet, skip all duplicate values to avoid duplicate triplets. But don't skip the first occurrence — you need it.
  • Confusing "return all unique triplets" with "return all triplets." If the input has duplicates like [-1, -1, 2], you should only return [-1, -1, 2] once, not twice.
  • Not handling the case where no triplet exists. Return an empty list, not `null` or an error.
  • Off-by-one in the outer loop: using range(len(nums)) instead of range(len(nums) - 2). The last two elements can't be the first element of a triplet since you need at least two elements after them.