TExcelTAD
Home › Parameterized & Fine-Grained Complexity › 3SUM and 3SUM-Hardness

3SUM and 3SUM-Hardness

3SUM: given nn integers, are there three of them, at different positions, with a+b+c=0a + b + c = 0? It is an interview classic (3Sum in the practice area), solvable in O(n2)O(n^2) time by sorting and sweeping two pointers. Whether O(n2−ε)O(n^{2 - \varepsilon}) is possible is one of the central open questions of fine-grained complexity. Gajentaan and Overmars (1995) noticed that a long list of problems in computational geometry, all with stubborn Θ(n2)\Theta(n^2) algorithms, are at least as hard as 3SUM. Their notion of 3SUM-hardness became the template for the whole field.

The quadratic algorithm

Sort the numbers. For each ii, look for a pair among the later positions summing to −ai-a_i by moving two pointers inward: if the sum is too small, advance the left pointer; if too large, retreat the right one. Each sweep takes O(n)O(n) steps, so the total is O(n2)O(n^2) after sorting.

text
3SUM(a[1..n])
1  sort a
2  for i = 1 to n - 2
3      lo = i + 1;  hi = n
4      while lo < hi
5          s = a[i] + a[lo] + a[hi]
6          if s = 0:  return (a[i], a[lo], a[hi])
7          if s < 0:  lo = lo + 1  else  hi = hi - 1
8  return NONE

Correctness. Fix ii and suppose ai+ap+aq=0a_i + a_p + a_q = 0 with i<p<qi < p < q. We show that the invariant lo≤plo \le p and q≤hiq \le hi holds until the sweep reports a zero sum. It holds at the start. If lo<plo < p and hi>qhi > q, either move keeps it. If lo<plo < p and hi=qhi = q, the sum is ai+alo+aq≤ai+ap+aq=0a_i + a_{lo} + a_q \le a_i + a_p + a_q = 0, so either it is zero (a solution is reported) or lolo advances, which keeps lo≤plo \le p. Symmetrically, if lo=plo = p and hi>qhi > q, the sum is at least 0 and either it is zero or hihi retreats. Since hi−lohi - lo shrinks at every step, the sweep reaches lo=plo = p, hi=qhi = q at the latest and reports a zero sum. □\square

The program checks the sweep against the cubic brute force on random inputs, counting steps.

python · try it yourself
import random

def three_sum_sweep(a):
    a = sorted(a)
    steps = 0
    for i in range(len(a) - 2):
        lo, hi = i + 1, len(a) - 1
        while lo < hi:
            steps += 1
            s = a[i] + a[lo] + a[hi]
            if s == 0:
                return (a[i], a[lo], a[hi]), steps
            if s < 0:
                lo += 1
            else:
                hi -= 1
    return None, steps

def three_sum_cubic(a):
    n, steps = len(a), 0
    for i in range(n):
        for j in range(i + 1, n):
            for k in range(j + 1, n):
                steps += 1
                if a[i] + a[j] + a[k] == 0:
                    return True, steps
    return False, steps

rng = random.Random(6)
print("  n       range  triple found              sweep steps  cubic steps  agree")
for n, R in [(60, 10**3), (60, 10**7), (120, 10**3), (120, 10**9)]:
    a = rng.sample(range(-R, R), n)
    t, s1 = three_sum_sweep(a)
    c, s2 = three_sum_cubic(a)
    print(f"{n:4} {R:>11}  {str(t):26} {s1:10} {s2:12}  {(t is not None) == c}")
  n       range  triple found              sweep steps  cubic steps  agree
  60        1000  (-820, 175, 645)                  261         3157  True
  60    10000000  None                             1711        34220  True
 120        1000  (-988, 18, 970)                    66         2437  True
 120  1000000000  None                             7021       280840  True

With a small range triples summing to zero are plentiful and both methods stop early; with a large range there is often no solution and both must finish, at ∼n22\sim\frac{n^2}{2} steps against ∼n36\sim\frac{n^3}{6}.

In C++

The sweep in C++ on 5000 random integers of magnitude up to 101510^{15} (so that a random zero triple is very unlikely), with one planted triple of small numbers. Its smallest member sits near the middle of the sorted order, so about half of the sweeps fail before the planted triple is found.

cpp · try it yourself
#include <algorithm>
#include <cstdio>
#include <vector>

int main() {
    const int n = 5000;
    std::vector<long long> a;
    unsigned long long s = 2024;
    auto rnd = [&]() { s = s * 6364136223846793005ULL + 1442695040888963407ULL; return (long long)(s >> 2); };
    while ((int)a.size() < n - 3) a.push_back(rnd() % 2000000000000000LL - 1000000000000000LL);
    a.push_back(-66666); a.push_back(12345); a.push_back(54321);              // a planted solution
    std::sort(a.begin(), a.end());
    long long steps = 0;
    for (int i = 0; i + 2 < n; i++) {
        int lo = i + 1, hi = n - 1;
        while (lo < hi) {
            steps++;
            long long sum = a[i] + a[lo] + a[hi];
            if (sum == 0) {
                std::printf("found %lld + %lld + %lld = 0 after %lld steps (n^2/2 = %lld)\n",
                            a[i], a[lo], a[hi], steps, (long long)n * n / 2);
                return 0;
            }
            if (sum < 0) lo++; else hi--;
        }
    }
    std::printf("none after %lld steps\n", steps);
}
found -66666 + 12345 + 54321 = 0 after 9331146 steps (n^2/2 = 12500000)

The 3SUM conjecture and what is known

3SUM conjecture (modern form). For every ε>0\varepsilon > 0, 3SUM on nn integers in {−n3,…,n3}\{-n^3, \ldots, n^3\} has no O(n2−ε)O(n^{2 - \varepsilon}) algorithm, even randomized, on the word RAM.

The restriction to a polynomial range loses nothing: hashing reduces general integer 3SUM to this range. The conjecture allows logarithmic improvements, and those are known (stated):

Result Model
O(n2(log⁡log⁡n)2/log⁡2n)O(n^2 (\log \log n)^2 / \log^2 n) expected integers, word RAM (Baran, Demaine and Pătrașcu, 2005)
O(n2/(log⁡n/log⁡log⁡n)2/3)O(n^2 / (\log n / \log \log n)^{2/3}) real numbers, real RAM (Grønlund and Pettie, 2014)
O(n3/2log⁡n)O(n^{3/2} \sqrt{\log n}) comparisons decision trees (Grønlund and Pettie, 2014)
n2(log⁡log⁡n)O(1)/log⁡2nn^2 (\log \log n)^{O(1)} / \log^2 n real numbers (Chan, 2018)

The decision-tree result is striking: a quadratic algorithm may be needed even though O(n3/2)O(n^{3/2}) well-chosen comparisons certify the answer. An earlier conjecture that 3SUM needs Ω(n2)\Omega(n^2) time in the real-RAM model was refuted by these results; the current conjecture asks only for n2−o(1)n^{2 - o(1)}.

Geometry: collinear points

3POINTS-ON-LINE: given nn points in the plane, are three of them collinear? The obvious algorithm checks all triples, O(n3)O(n^3); sorting the slopes around each point gives O(n2log⁡n)O(n^2 \log n), and duality plus line arrangements gives O(n2)O(n^2).

Reduction from 3SUM (Gajentaan and Overmars, 1995). Map each number xx to the point (x,x3)(x, x^3) on the cubic curve. For distinct a,b,ca, b, c, the points (a,a3),(b,b3),(c,c3)(a, a^3), (b, b^3), (c, c^3) are collinear iff

b3−a3b−a=c3−a3c−a  ⟺  b2+ab+a2=c2+ac+a2  ⟺  (b−c)(a+b+c)=0  ⟺  a+b+c=0.\frac{b^3 - a^3}{b - a} = \frac{c^3 - a^3}{c - a} \iff b^2 + ab + a^2 = c^2 + ac + a^2 \iff (b - c)(a + b + c) = 0 \iff a + b + c = 0.

The map takes linear time, so an O(n2−ε)O(n^{2 - \varepsilon}) collinearity algorithm would give the same for 3SUM (with distinct numbers; repeated values are handled separately). The program verifies the equivalence with exact integer cross products.

python · try it yourself
import random
from itertools import combinations

def collinear_triple(points):
    for p, q, r in combinations(points, 3):
        if (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]) == 0:
            return (p[0], q[0], r[0])
    return None

def zero_triple(a):
    for x, y, z in combinations(a, 3):
        if x + y + z == 0:
            return (x, y, z)
    return None

rng = random.Random(11)
for trial in range(6):
    a = rng.sample(range(-40, 41), 9)
    pts = [(x, x ** 3) for x in a]
    print(f"{sorted(a)}: 3SUM {zero_triple(a)}, collinear x-coordinates {collinear_triple(pts)}")
[-17, -16, 17, 19, 25, 31, 35, 36, 40]: 3SUM None, collinear x-coordinates None
[-29, -28, -22, -17, -2, 17, 20, 28, 38]: 3SUM None, collinear x-coordinates None
[-39, -35, -33, -32, -20, 10, 17, 27, 36]: 3SUM None, collinear x-coordinates None
[-37, -36, -16, -15, -10, 1, 16, 19, 36]: 3SUM (36, -37, 1), collinear x-coordinates (36, -37, 1)
[-40, -30, -11, -5, -3, 12, 18, 23, 26]: 3SUM (-30, 18, 12), collinear x-coordinates (-30, 18, 12)
[-37, -32, -30, -11, -8, -4, 0, 25, 30]: 3SUM (30, -30, 0), collinear x-coordinates (30, -30, 0)

Each row shows the same triple (or none) from both sides of the reduction.

More 3SUM-hard problems

From Gajentaan and Overmars and later work (stated):

  • Geometry: whether a set of line segments has a line separating them into two nonempty sets, minimum-area triangle among nn points, whether a union of triangles covers a given triangle, motion planning of a segment among polygonal obstacles, visibility between segments.
  • Combinatorics on numbers: 3SUM' (three lists), Convolution 3SUM (ai+aj=ai+ja_i + a_j = a_{i+j}; Pătrașcu, 2010, with randomized reductions both ways), and Exact Triangle in weighted graphs in its version with n1.5n^{1.5} edges.
  • Graphs and data structures: Pătrașcu (2010) used Convolution 3SUM to show that listing triangles in a graph with mm edges needs m4/3−o(1)m^{4/3 - o(1)} time, and gave polynomial lower bounds for dynamic problems such as dynamic reachability, under the 3SUM conjecture.

These reductions are the 3SUM branch of The Reduction Web.

Test yourself

Why does the two-pointer sweep for a fixed ii never skip a valid pair (p,q)(p, q)?

  1. Because the array has no duplicates
  2. Because, with the array sorted, the left pointer only advances when the sum is too small and the right one only retreats when it is too large, so neither passes its target before the other reaches its own
  3. Because it checks all pairs
  4. Because it uses hashing

In the reduction from 3SUM to collinear points, where is a number xx mapped?

  1. (x,x)(x, x)
  2. (x,x2)(x, x^2)
  3. (x,x3)(x, x^3)
  4. (x,1/x)(x, 1/x)

What does the modern 3SUM conjecture claim?

  1. 3SUM needs Ω(n2)\Omega(n^2) time in every model
  2. No O(n2−ε)O(n^{2-\varepsilon}) algorithm exists for any ε>0\varepsilon > 0; logarithmic speedups are allowed and known
  3. 3SUM is NP-hard
  4. 3SUM needs n3n^3 time

Which result shows that the comparison complexity of 3SUM is below n2n^2?

  1. Baran, Demaine and Pătrașcu (2005)
  2. Grønlund and Pettie (2014): decision trees of depth O(n3/2log⁡n)O(n^{3/2} \sqrt{\log n})
  3. Gajentaan and Overmars (1995)
  4. Williams (2005)