Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

3SUM & the k-SUM Problem

From quadratic 3SUM with two pointers to the 3SUM conjecture.

"Are there three numbers in this list that sum to zero?" takes one line to ask and O(n2)O(n^2) time to answer with two pointers. Three decades of work have shaved only logarithmic factors off that bound, and the conjecture that nothing truly faster exists now carries the weight of lower bounds for dozens of problems, from collinear points to dynamic data structures.

What you’ll learn

  • Define 3SUM and k-SUM with their equivalent variants, and solve k-SUM in O(n⌈k/2⌉)O(n^{\lceil k/2\rceil}) time (with an extra log⁡n\log n for even kk) by meet in the middle.
  • State Erickson's Ω(n⌈k/2⌉)\Omega(n^{\lceil k/2\rceil}) lower bound with its model, and explain why it rules out neither faster algorithms nor shallower trees with richer queries.
  • State the 3SUM conjecture precisely and prove that deciding whether three of nn points are collinear is 3SUM-hard.
  • Summarize the logarithmic speedups and decision-tree results up to 2025, and the open problems they leave.

3SUM and its relatives

The variants are equivalent up to linear-time reductions. A target tt becomes 0 by replacing each integer aa with 3a−t3a-t. The form a+b=ca+b=c is the three-list form with CC negated. Three lists become one by shifting: replace a∈Aa\in A by a+Ma+M, b∈Bb\in B by b+3Mb+3M and c∈Cc\in C by c−4Mc-4M for a large MM. Of the ten ways to pick three offsets from {M,3M,−4M}\{M,3M,-4M\}, only M+3M−4MM+3M-4M is zero, so with M>3max⁡∣ai∣M>3\max\abs{a_i} only triples with one element from each list can cancel.

Two quadratic algorithms are standard. Sort and two pointers (the Optimized lesson) runs in Θ(n2)\Theta(n^2) worst-case time using only additions and comparisons, so it works on reals. Hashing fixes ii and asks, for each j>ij>i, whether −ai−aj-a_i-a_j was seen between them: O(n2)O(n^2) expected time on the word RAM.

python
def three_sum_hash(a):
    """Is there i < j < k with a[i] + a[j] + a[k] == 0? O(n^2) expected time."""
    n = len(a)
    for i in range(n):
        seen = set()                     # values a[i+1..j-1]
        for j in range(i + 1, n):
            if -a[i] - a[j] in seen:
                return True
            seen.add(a[j])
    return False

print(three_sum_hash([5, -7, 3, 9, 2]))   # True: 5 + (-7) + 2 == 0
Check your understanding

All nn inputs are integers in [−n,n][-n,n]. What is the fastest correct way to decide 3SUM?

  1. Sort and two pointers: Θ(n2)\Theta(n^2) is the best known for every input range
  2. Hashing, which runs in O(n)O(n) expected time
  3. Multiply the polynomial f(x)=∑ixai+nf(x)=\sum_i x^{a_i+n} by itself twice with the FFT and read the coefficient of x3nx^{3n}: O(nlog⁡n)O(n\log n)
  4. Sort, then binary search for −ai−aj-a_i-a_j: O(nlog⁡n)O(n\log n)
Show the answer

C. Multiply the polynomial f(x)=∑ixai+nf(x)=\sum_i x^{a_i+n} by itself twice with the FFT and read the coefficient of x3nx^{3n}: O(nlog⁡n)O(n\log n)

The coefficient of x3nx^{3n} in f(x)3f(x)^3 counts ordered triples (repeats included) with sum 0; subtracting the triples that reuse a position, read off f(x2)f(x)f(x^2)f(x) and f(x3)f(x^3), leaves the genuine ones. With values in [−U,U][-U,U] this costs O(n+Ulog⁡U)O(n+U\log U), so hard instances need U≥n2−o(1)U\ge n^{2-o(1)}: the integer form of the conjecture is stated for ranges such as [−n3,n3][-n^3,n^3]. See The Fast Fourier Transform.

k-SUM: meet in the middle, and a matching lower bound

DerivationProof
  1. O(nmlog⁡nm)+O(nm)=O(nk/2log⁡n)O\big(n^m\log n^m\big)+O\big(n^m\big)=O\big(n^{k/2}\log n\big)

    Even k=2mk=2m. Let LL hold all nmn^m sums with one element from each of A1,…,AmA_1,\dots,A_m, and RR the nmn^m sums from Am+1,…,A2mA_{m+1},\dots,A_{2m}. A solution is exactly a pair x∈Lx\in L, y∈Ry\in R with x+y=0x+y=0. Sort both, then run the pair-sum walk on two sorted lists:

  2. O(nmlog⁡n)+n⋅O(nm)=O(nm+1)=O(n⌈k/2⌉)O\big(n^m\log n\big)+n\cdot O\big(n^m\big)=O\big(n^{m+1}\big)=O\big(n^{\lceil k/2\rceil}\big)

    Odd k=2m+1k=2m+1. Build and sort LL and RR from the first 2m2m lists once. For each of the nn elements a∈Aka\in A_k, walk LL and RR looking for x+y=−ax+y=-a, in linear time each:

  3. T3(n)=O(n2),T4(n)=O(n2log⁡n),T5(n)=O(n3)T_3(n)=O(n^2),\qquad T_4(n)=O(n^2\log n),\qquad T_5(n)=O(n^3)

    For k=3k=3 (m=1m=1), LL and RR are sorted copies of two lists, and the bound is the familiar Θ(n2)\Theta(n^2). Replacing the sorted lists by a hash set of RR removes the logarithm for even kk, in expectation.

python
def four_sum_exists(a, b, c, d):
    """Is there w + x + y + z == 0 with w in a, x in b, y in c, z in d?"""
    left = sorted(w + x for w in a for x in b)      # n^2 sums, sorted
    right = sorted(y + z for y in c for z in d)
    i, j = 0, len(right) - 1
    while i < len(left) and j >= 0:                 # pair sum on two sorted lists
        s = left[i] + right[j]
        if s == 0:
            return True
        if s < 0:
            i += 1        # left[i] is too small even with the largest right sum left
        else:
            j -= 1        # right[j] is too big even with the smallest left sum left
    return False

4-SUM in O(n2log⁡n)O(n^2\log n) time and O(n2)O(n^2) space; the same walk as pair sum, on lists of half-sums.

The proof is an adversary argument. Very roughly, the adversary builds an input with Ω(n⌈k/2⌉)\Omega(n^{\lceil k/2\rceil}) critical kk-tuples: each could be turned into a solution by an infinitesimal perturbation (Erickson works with formal infinitesimals) that changes the sign of no other query. A kk-linear query notices such a perturbation only if its hyperplane is that tuple's own equation, so a correct tree must ask about every critical tuple separately. For odd kk the bound matches meet in the middle exactly.

The theorem is about a model, and the model matters. Grønlund and Pettie (2014) showed that 3SUM has 4-linear decision trees of depth O(n3/2log⁡n)O(n^{3/2}\sqrt{\log n}). Kane, Lovett and Moran (2018) went further: for every constant kk, k-SUM has linear decision trees with O(nlog⁡2n)O(n\log^2 n) queries, each comparing the sums of two kk-subsets, so every query is 2k2k-sparse with coefficients in {−1,0,1}\{-1,0,1\}. Allowing a few more variables per query collapses the bound from n2n^2 to nearly nn.

Check your understanding

Kane, Lovett and Moran decide 3SUM with O(nlog⁡2n)O(n\log^2n) comparison queries. Why does this not give an O(nlog⁡2n)O(n\log^2 n)-time algorithm?

  1. Each comparison query costs Θ(n)\Theta(n) time to evaluate
  2. A decision tree counts only queries: deciding which query to ask next, and building the tree, is free in the model but costs time in a real algorithm
  3. The bound is amortized over many inputs
  4. It only works for integer inputs
Show the answer

B. A decision tree counts only queries: deciding which query to ask next, and building the tree, is free in the model but costs time in a real algorithm

Decision-tree depth measures information, not computation. The tree may be different for every nn and arbitrarily hard to construct, and the work of choosing each next query is not charged. Turning shallow trees into fast algorithms is exactly where the logarithmic-speedup papers spend their effort.

The 3SUM conjecture and 3SUM-hardness

Gajentaan and Overmars (1995) introduced 3SUM-hardness to explain why so many problems in computational geometry were stuck at quadratic time. Their original question was whether Θ(n2)\Theta(n^2) is optimal; Grønlund and Pettie (2014) refuted that strong form with algorithms running in n2n^2 divided by a polylogarithm. The modern conjecture asks for a polynomial improvement and is still open. The cleanest reduction turns sums into slopes.

DerivationProof
  1. a3−b3a−b=a2+ab+b2\frac{a^3-b^3}{a-b}=a^2+ab+b^2

    For distinct aa and bb, the slope between (a,a3)(a,a^3) and (b,b3)(b,b^3) is

  2. a2+ab+b2=a2+ac+c2  ⟺  a(b−c)+(b−c)(b+c)=0a^2+ab+b^2=a^2+ac+c^2\iff a(b-c)+(b-c)(b+c)=0

    Three distinct points are collinear exactly when the slopes from (a,a3)(a,a^3) to the other two agree:

  3. (b−c)(a+b+c)=0  ⟺  a+b+c=0(b-c)(a+b+c)=0\iff a+b+c=0

    Factor out b−cb-c, which is nonzero because the numbers are distinct:

  4. T3SUM(n) ≤ Tcollinear(n)+O(nlog⁡n)T_{3\text{SUM}}(n)\ \le\ T_{\text{collinear}}(n)+O(n\log n)

    Repeated values are handled separately: a solution that uses some value twice, 2a+c=02a+c=0, is found in O(nlog⁡n)O(n\log n) time by sorting. So a subquadratic collinearity algorithm yields a subquadratic 3SUM algorithm.

Think first The numbers −3,1,2-3,1,2 sum to 0. Check that (−3,−27)(-3,-27), (1,1)(1,1) and (2,8)(2,8) lie on one line. Why would a parabola, a↦(a,a2)a\mapsto(a,a^2), not work?

The slopes are 1+271+3=7\frac{1+27}{1+3}=7, 8−12−1=7\frac{8-1}{2-1}=7 and 8+272+3=7\frac{8+27}{2+3}=7: one line of slope 7, and a2+ab+b2=9−3+1=7a^2+ab+b^2=9-3+1=7 as predicted. On a parabola the slope between (a,a2)(a,a^2) and (b,b2)(b,b^2) is a+ba+b, so equal slopes from aa force b=cb=c: no three distinct points of a parabola are ever collinear, and the reduction would say nothing.

The same paper shows that many other problems are 3SUM-hard, among them whether three of nn lines pass through one point (the dual of collinearity), whether a union of triangles has a hole, and planar motion-planning questions. Pătraşcu (2010) proved, by a randomized reduction, that the convolution version, find i,ji,j with a[i]+a[j]=a[i+j]a[i]+a[j]=a[i+j], is as hard as 3SUM, and from it derived polynomial lower bounds for dynamic data structures and for listing the triangles of a graph. Today the 3SUM conjecture is one of the three pillars of fine-grained complexity, beside the APSP conjecture and SETH.

Shaving logarithms: the state of the art

YearResultModel
1995/1999Erickson: Ω(n⌈k/2⌉)\Omega(n^{\lceil k/2\rceil}) queries for k-SUMkk-linear decision trees
2005Baran, Demaine & Pătraşcu: O(n2(log⁡log⁡n)2/log⁡2n)O\big(n^2(\log\log n)^2/\log^2 n\big) expected timeintegers, word RAM
2014Grønlund & Pettie: depth O(n3/2log⁡n)O(n^{3/2}\sqrt{\log n}); time O(n2/(log⁡n/log⁡log⁡n)2/3)O\big(n^2/(\log n/\log\log n)^{2/3}\big) deterministic, O(n2(log⁡log⁡n)2/log⁡n)O\big(n^2(\log\log n)^2/\log n\big) randomizedreals: 4-linear trees; real RAM
2018Chan: O(n2(log⁡log⁡n)O(1)/log⁡2n)O\big(n^2(\log\log n)^{O(1)}/\log^2 n\big) timereals, real RAM
2018Kane, Lovett & Moran: O(nlog⁡2n)O(n\log^2n) queries for k-SUM, any constant kk2k2k-sparse comparison queries
Algorithms creep below n2n^2 by logarithmic factors; decision trees with slightly richer queries drop to nearly linear depth.

Much of this rests on Fredman's trick (1976): a+b<a′+b′a+b<a'+b' exactly when a−a′<b′−ba-a'<b'-b. A comparison between two sums becomes a comparison between two differences, one from each side. Split the sorted input into blocks of gg elements; the differences inside each block can be sorted once and reused across many scans. That idea is at the core of Grønlund and Pettie's shallow trees and, combined with word-level or table-lookup tricks, of the faster algorithms.

How much do these logarithms buy? At n=106n=10^6, (log⁡2n/log⁡2log⁡2n)2≈21(\log_2 n/\log_2\log_2 n)^2\approx21, before constant factors that are typically large. The practical algorithm remains sort and two pointers; the logarithmic results matter because they show that the comparisons a naive argument would charge are not the true bottleneck.

Key takeaways

  • 3SUM takes Θ(n2)\Theta(n^2) worst-case time by sorting and two pointers, or O(n2)O(n^2) expected by hashing; small integer ranges fall to the FFT, so hard instances have values of size around n2n^2 or more.
  • Meet in the middle solves k-SUM in O(n⌈k/2⌉)O(n^{\lceil k/2\rceil}) time (times log⁡n\log n for even kk), and Erickson proved this optimal for kk-linear decision trees, but 4-linear and 2k2k-sparse comparison trees need far fewer queries.
  • The 3SUM conjecture says no O(n2−ε)O(n^{2-\varepsilon}) algorithm exists; only its original "exactly n2n^2" form has fallen, to n2/polylog⁡nn^2/\operatorname{polylog} n algorithms.
  • 3SUM-hardness transfers the conjecture: mapping a↦(a,a3)a\mapsto(a,a^3) makes "three collinear points" equivalent to "a+b+c=0a+b+c=0".

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

With meet in the middle, how much time does 5-SUM on five lists of nn numbers take?

  1. O(n2.5)O(n^{2.5})
  2. O(n5)O(n^5)
  3. O(n3)O(n^3)
  4. O(n2log⁡n)O(n^2\log n)
Show the answer

C. O(n3)O(n^3)

k=5=2⋅2+1k=5=2\cdot2+1: sort the n2n^2 sums of lists 1–2 and of lists 3–4, then for each of the nn elements of list 5 run a linear walk over the two sorted lists of n2n^2 sums: n⋅n2=n3=n⌈5/2⌉n\cdot n^2=n^3=n^{\lceil5/2\rceil}.

Question 2

Which statement about 3SUM is true as of 2025?

  1. An O(n1.99)O(n^{1.99})-time algorithm is known
  2. It is proven to need Ω(n2)\Omega(n^2) time on the word RAM
  3. Its decision-tree complexity is Θ(n2)\Theta(n^2) for linear queries of every kind
  4. It can be solved in n2n^2 divided by a polylogarithm, but no O(n2−ε)O(n^{2-\varepsilon}) algorithm is known
Show the answer

D. It can be solved in n2n^2 divided by a polylogarithm, but no O(n2−ε)O(n^{2-\varepsilon}) algorithm is known

Logarithmic speedups exist for integers (2005) and reals (2014, 2018). The conjecture that no polynomial speedup exists remains open, and it underlies many conditional lower bounds.

Question 3

The reduction from 3SUM to collinearity maps aa to (a,a3)(a,a^3). Why not to (a,a2)(a,a^2)?

  1. Squares lose the sign of aa, but the reduction would otherwise work
  2. No three distinct points of a parabola are collinear, so collinearity would carry no information
  3. Squares are too small to represent in O(log⁡n)O(\log n)-bit words
  4. It would also work; cubes are just conventional
Show the answer

B. No three distinct points of a parabola are collinear, so collinearity would carry no information

The slope between (a,a2)(a,a^2) and (b,b2)(b,b^2) is a+ba+b; equal slopes from aa force b=cb=c. With cubes the slope is a2+ab+b2a^2+ab+b^2, and equal slopes factor into (b−c)(a+b+c)=0(b-c)(a+b+c)=0.

Question 4

Which of these problems is 3SUM-hard, so that an O(n2−ε)O(n^{2-\varepsilon}) algorithm for it would refute the 3SUM conjecture?

  1. Sorting nn numbers
  2. Deciding whether two of nn numbers sum to 0
  3. Deciding whether three of nn lines in the plane pass through a common point
  4. Finding the closest pair among nn points in the plane
Show the answer

C. Deciding whether three of nn lines in the plane pass through a common point

Concurrent lines are the projective dual of collinear points, one of Gajentaan and Overmars's original 3SUM-hard problems. The other three take O(nlog⁡n)O(n\log n) time, which refutes nothing.

Further reading

  • A. Gajentaan & M. H. Overmars, "On a class of O(n2)O(n^2) problems in computational geometry," Computational Geometry: Theory and Applications (1995).
  • J. Erickson, "Lower bounds for linear satisfiability problems," Chicago Journal of Theoretical Computer Science (1999); extended abstract at SODA 1995.
  • I. Baran, E. D. Demaine & M. Pătraşcu, "Subquadratic algorithms for 3SUM," WADS 2005; Algorithmica (2008).
  • A. Grønlund & S. Pettie, "Threesomes, degenerates, and love triangles," FOCS 2014; Journal of the ACM (2018).
  • D. M. Kane, S. Lovett & S. Moran, "Near-optimal linear decision trees for k-SUM and related problems," STOC 2018; Journal of the ACM (2019).