LeetCode 15 · Medium

3Sum Explained (LeetCode 15)

Updated Nov 27, 2026 · 3 min read

Sort the array, then fix one number at a time and walk two pointers in from both ends of the rest. If the sum is too small, move the left pointer right; if it's too big, move the right pointer left; if it's zero, record the triplet. Skip values you've already used and the duplicates disappear, for O(n^2) time.

Watch onYouTube

Key points

  • ●Checking every triple is O(n^3): about 4.5 billion triples for 3,000 numbers.
  • ●Sorting makes the sum move predictably as the pointers move.
  • ●Too small: move left. Too big: move right. Zero: record and move both.
  • ●Skip repeated fixed values and repeated pointer values to avoid duplicate triplets.
  • ●O(n^2) time, O(n) extra space for the sorted copy.
Step-by-step visual sheet: 3Sum
The full visual sheet, made with Edithly.Open the interactive sheet

The riddle: three numbers that cancel out

You get a list of whole numbers, some negative: 0, -2, 1, 2, -2, 1. Find every group of three numbers, taken from three different positions, that adds up to exactly zero. Each group of values should appear only once, even if the same values show up at other positions.

For this list the answer is [-2, 0, 2] and [-2, 1, 1]. That's LeetCode 15, 3Sum.

Notice that [-2, 1, 1] is fine. The two 1s sit at different positions. What's not fine is listing [-2, 0, 2] twice just because there are two -2s.

The slow way: try every triple

Three nested loops try every group of three. That's O(n^3). The problem allows up to 3,000 numbers, which is about 4.5 billion triples. On top of that, brute force gives you no clean way to drop duplicate triplets.

The idea: sort, fix one, squeeze two pointers

Sort the list first. Now the order means something: numbers on the left are small, numbers on the right are big.

Then for each position i, treat nums[i] as fixed and search the rest with two pointers:

  • left starts just after i
  • right starts at the end

Add the three up:

  • Total below zero? You need a bigger number, so move left right.
  • Total above zero? You need a smaller number, so move right left.
  • Total is zero? Record the triplet and move both pointers in.

Stop when the pointers meet. Since left always sits after i and before right, the three positions are automatically different.

Trace it on the example

Sorted, the list is [-2, -2, 0, 1, 1, 2].

Fixed left right Total Move
-2 -2 2 -2 too small, left++
-2 0 2 0 record [-2, 0, 2]
-2 1 1 0 record [-2, 1, 1]
-2 (second) skip, same fixed value
0 1 2 3 too big, right--
0 1 1 2 too big, pointers meet
1 1 2 4 too big, pointers meet

Two triplets, exactly the answer. Step 6 of the visual sheet above walks the same sorted list.

The code in Python

def three_sum(numbers):
    nums = sorted(numbers)
    result = []
    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        left, right = i + 1, len(nums) - 1
        while left < right:
            total = nums[i] + nums[left] + nums[right]
            if total < 0:
                left += 1
            elif total > 0:
                right -= 1
            else:
                result.append([nums[i], nums[left], nums[right]])
                left, right = left + 1, right - 1
                while left < right and nums[left] == nums[left - 1]:
                    left += 1
                while left < right and nums[right] == nums[right + 1]:
                    right -= 1
    return result

sorted() makes a copy, so the caller's list isn't changed. With fewer than three numbers the loop never runs and you get an empty list.

Complexity

  • Time: O(n^2). Sorting is O(n log n), then each fixed number gets one pointer pass of up to n steps.
  • Space: O(n) for the sorted copy, not counting the output.

From O(n^3) to O(n^2) by sorting first.

The trap to watch for

Duplicates, in both directions.

Skip too little and [-2, 0, 2] shows up twice, once for each -2. That's why the loop skips a fixed value equal to the one before it, and why both pointers step past repeats after a match.

Skip too much and you lose real answers. If you removed duplicate values before searching, [-2, 1, 1] would vanish, because it needs both 1s. The rule is to skip equal values only where they'd rebuild a triplet you already recorded. And [0, 0, 0, 0] should return just [[0, 0, 0]].

Frequently asked questions

Why do you sort the array in 3Sum?

Sorting puts the numbers in order, so moving the left pointer right always makes the sum bigger and moving the right pointer left always makes it smaller. That lets you rule out a whole range of pairs with each step instead of trying them all. It also puts equal values next to each other, which makes skipping duplicates easy.

How does 3Sum avoid duplicate triplets?

In two places. Skip a fixed value if it equals the one before it, and after recording a match, move each pointer past any values equal to the ones just used. Equal values can still appear inside one triplet, like [-2, 1, 1], because they come from different positions.

What is the time complexity of 3Sum?

O(n^2). Sorting is O(n log n), and for each of the n fixed numbers the two pointers make one pass of at most n steps. The sorted copy uses O(n) extra space.

How is 3Sum related to Two Sum?

Fix one number and 3Sum becomes a two-number search for the value that cancels it out. Because the array is sorted, that inner search can be done with two pointers instead of a hash map.

Turn any problem or document into a visual sheet like this one

Paste a LeetCode problem, a PDF or a link into Edithly and get a step-by-step sheet you can study, share or quiz yourself on.

Make this sheet in Edithly, free