3Sum solution explained

The usual 3Sum solution sorts the array, fixes each value in turn as the smallest member of a triple, and then closes in on the remaining two with a left and a right pointer, skipping equal values so no triple is reported twice. Sorting costs O(n log n) and the pointer scans cost O(n²), so the whole thing is O(n²) time with no extra structure besides the output.

By Published 8 min read

The task in plain terms

Given an array of integers, find all groups of three entries that sit at three different positions and add up to zero. Report each group by its values, and report each distinct combination of values only once, even when the array holds several copies that could form it. The order of the groups and the order inside each group usually do not matter, but confirm that, since it affects how you compare answers in tests.

Inputs made up for this walkthrough
ArrayTriplesNote
[6, -5, 3, -1, 2, -2][-5, -1, 6], [-5, 2, 3], [-2, -1, 3]One value can belong to several answers
[-2, -2, 4, 1, 1][-2, -2, 4], [-2, 1, 1]Repeated values may appear inside one triple
[0, 0, 0, 0][0, 0, 0]Four zeros, still one triple
[1, 2, -2, -1]noneNo three of these reach zero
Inputs made up for this walkthrough. Scroll sideways on a small screen.

Ask whether the target is always zero, whether you may sort the input in place, whether the output must be in a particular order, and how big the array can be. If it can hold tens of thousands of values, a cubic method is out, and saying so early shows you sized the problem before writing code.

Why interviewers like this one

3Sum looks like Two Sum with one more number, and that is the trap. Bolting a hash map onto every pair gets the speed but makes duplicate handling messy. The cleaner route is to see that sorting turns the inner problem into a two-pointer sweep, and that the same sort makes duplicates sit next to each other so they are easy to skip. Interviewers watch for both insights, and most lost points come from the duplicate handling rather than from the main idea.

Follow-ups that often come next

  • Any target, not just zero. Replace zero with target minus the fixed value in the inner sweep. Nothing else changes.
  • Closest sum to a target. Run the same sweep, keep the sum with the smallest distance to the target, and move the pointer that brings the sum toward it.
  • Count triples whose sum is below a bound. When the left and right pointers give a small enough sum, every index between them also works with the left one, so add right minus left at once.
  • Four numbers. Add another outer loop with the same skip rule. That gives O(n³), and the pattern generalizes to k numbers by recursion down to the two-pointer base case.
  • No sorting allowed. For each fixed index, use a hash set for the inner pair and store each found triple in sorted form inside a set of results. Still O(n²) on average, with more memory.

Brute force: every triple, then remove repeats

Three nested loops visit every choice of three positions. When a triple sums to zero, sort its three values and add the tuple to a set, which drops repeated combinations. This is O(n³) time and O(k) space for the k answers. It is easy to trust and makes a solid checker for the faster version.

def zero_triples_slow(values):
    found = set()
    n = len(values)
    for i in range(n):
        for j in range(i + 1, n):
            for k in range(j + 1, n):
                if values[i] + values[j] + values[k] == 0:
                    found.add(tuple(sorted((values[i], values[j], values[k]))))
    return sorted(list(t) for t in found)
Brute force, O(n³) time. Sorted tuples in a set remove repeats.

Optimal approach: sort, fix one, sweep two

Sort the array. Walk an index i from the left, treating the value there as the smallest member of the triple. The other two must come from the part to its right and add up to the negative of that value. In a sorted range, that is a two-pointer job: start one pointer just after i and one at the end, move the left pointer right when the sum is too small and the right pointer left when it is too big. A match is recorded and both pointers move inward.

Duplicates are handled in two places. Skip i when its value equals the value just before it, because every triple it could start has already been found. After recording a match, move the left pointer past all copies of its value, which keeps the same pair from being found twice. One pruning check also helps: once the fixed value is positive, nothing to its right can bring the sum back to zero, so stop.

def zero_triples(values):
    nums = sorted(values)
    out = []
    n = len(nums)
    for i in range(n - 2):
        if nums[i] > 0:
            break
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        lo, hi = i + 1, n - 1
        while lo < hi:
            total = nums[i] + nums[lo] + nums[hi]
            if total < 0:
                lo += 1
            elif total > 0:
                hi -= 1
            else:
                out.append([nums[i], nums[lo], nums[hi]])
                lo += 1
                hi -= 1
                while lo < hi and nums[lo] == nums[lo - 1]:
                    lo += 1
    return out
Python: sort plus two pointers, O(n²) time.
#include <algorithm>
#include <array>
#include <vector>

std::vector<std::array<int, 3>> zeroTriples(std::vector<int> nums) {
    std::sort(nums.begin(), nums.end());
    std::vector<std::array<int, 3>> out;
    const int n = static_cast<int>(nums.size());
    for (int i = 0; i + 2 < n; ++i) {
        if (nums[i] > 0) break;
        if (i > 0 && nums[i] == nums[i - 1]) continue;
        int lo = i + 1, hi = n - 1;
        while (lo < hi) {
            const long long total = 0LL + nums[i] + nums[lo] + nums[hi];
            if (total < 0) {
                ++lo;
            } else if (total > 0) {
                --hi;
            } else {
                out.push_back({nums[i], nums[lo], nums[hi]});
                ++lo;
                --hi;
                while (lo < hi && nums[lo] == nums[lo - 1]) ++lo;
            }
        }
    }
    return out;
}
C++17: the same algorithm on a sorted copy.

The C++ version adds the three values as long long so that large inputs cannot overflow a 32-bit sum. Python integers have no such limit.

def closest_triple_sum(values, target):
    nums = sorted(values)
    best = nums[0] + nums[1] + nums[2]
    for i in range(len(nums) - 2):
        lo, hi = i + 1, len(nums) - 1
        while lo < hi:
            total = nums[i] + nums[lo] + nums[hi]
            if abs(total - target) < abs(best - target):
                best = total
            if total < target:
                lo += 1
            elif total > target:
                hi -= 1
            else:
                return total
    return best
Follow-up: the sum of three values closest to a target, same sweep.

Cost of each approach

Time and extra space, ignoring the output list
ApproachTimeExtra spaceTrade-off
Every triple plus a result setO(n³)O(k) for k answersSimple, too slow beyond small arrays
Fix one, hash set for the pairO(n²) averageO(n)Works without sorting, fiddly repeat handling
Sort, fix one, two pointersO(n²)O(1) beyond the sortThe expected answer
Closest-sum variantO(n²)O(1) beyond the sortSame sweep, different bookkeeping
Time and extra space, ignoring the output list. Scroll sideways on a small screen.

Cases to test by hand

  • Fewer than three values: the answer is empty, and the loop bounds must not read past the end.
  • All zeros, such as [0, 0, 0, 0]: exactly one triple.
  • Repeated negatives forming a triple, such as [-2, -2, 4].
  • Many copies of the same pair, as in [-2, 1, 1, 1, 1]: the pair (1, 1) should be reported once.
  • Only positive or only negative values: no triple, and the early break should end quickly for positives.
  • Large magnitudes in C++ or Java, where three 32-bit values can overflow when added.

Typical mistakes

  • Skipping duplicates of the fixed value by comparing with the next element instead of the previous one, which throws away triples like [-2, -2, 4].
  • Forgetting to move past repeated left values after a match, so the same triple is added several times.
  • Collecting every match and deduplicating with a set at the end. It works, but it hides that the sweep produced repeats, and interviewers usually ask you to prevent them instead.
  • Using a hash map per pair and claiming O(1) extra space.
  • Breaking out of the loop when the fixed value is zero rather than positive. [0, 0, 0] still needs that zero.

How to explain it out loud

Fictional example

Narrating 3Sum with the duplicate rules
Candidate
Checking every triple is cubic. If I sort first, I can fix one value and look for a pair to its right that cancels it, and in a sorted range that pair search is two pointers moving toward each other.
Candidate
To avoid repeats, I skip a fixed value equal to the previous one, and after a match I move the left pointer past copies of its value. Once the fixed value is positive, I can stop.
Candidate
That is quadratic overall. On -2, -2, 4, 1, 1 sorted, the first -2 finds both 4 with -2 and the pair of ones, and the second -2 is skipped.

Where to go from here

The two-pointer sweep on sorted data is the same move as the sorted follow-up in Two Sum, and Container With Most Water uses pointers from both ends with a different rule for which one moves. Skipping equal neighbors after a sort is also the middle approach in Contains Duplicate. Find all walkthroughs on the coding problems hub.

Drilling 3Sum with Natively

On Mac or Windows, Natively can read a problem like 3Sum from a screenshot while you practice and outline an approach with code, including the duplicate-skipping rules that most mistakes come from. Run a timed mock with it transcribing, and you can afterward reread whether you explained the skip rule before you coded it or patched it in later. The AI assistant for coding interviews page explains how this works.

Questions people ask

What is the optimal solution to 3Sum?

Sort the array, then for each index treat its value as the first member and look for a pair to its right that cancels it, using a left and a right pointer. Skip equal values so each triple appears once. It runs in O(n²) time.

How do you avoid duplicate triples in 3Sum?

Skip a fixed value when it equals the value just before it, and after each match move the left pointer past all copies of its value. Sorting puts duplicates next to each other, which makes both skips simple.

Can 3Sum be solved faster than O(n²)?

Only by small logarithmic factors, using research algorithms no interviewer expects, and it is widely believed that nothing is dramatically faster. In an interview, O(n²) with sorting and two pointers is the expected answer.

How is 3Sum different from Two Sum?

It needs every distinct answer rather than one, and it adds a third number. Fixing one value reduces it to a sorted Two Sum, which is why the two-pointer version fits so well.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP