3SUM and 3SUM-Hardness
3SUM: given integers, are there three of them, at different positions, with ? It is an interview classic (3Sum in the practice area), solvable in time by sorting and sweeping two pointers. Whether 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 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 , look for a pair among the later positions summing to 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 steps, so the total is after sorting.
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 NONECorrectness. Fix and suppose with . We show that the invariant and holds until the sweep reports a zero sum. It holds at the start. If and , either move keeps it. If and , the sum is , so either it is zero (a solution is reported) or advances, which keeps . Symmetrically, if and , the sum is at least 0 and either it is zero or retreats. Since shrinks at every step, the sweep reaches , at the latest and reports a zero sum.
The program checks the sweep against the cubic brute force on random inputs, counting steps.
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 steps against .
In C++
The sweep in C++ on 5000 random integers of magnitude up to (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.
#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 , 3SUM on integers in has no 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 |
|---|---|
| expected | integers, word RAM (Baran, Demaine and Pătrașcu, 2005) |
| real numbers, real RAM (Grønlund and Pettie, 2014) | |
| comparisons | decision trees (Grønlund and Pettie, 2014) |
| real numbers (Chan, 2018) |
The decision-tree result is striking: a quadratic algorithm may be needed even though well-chosen comparisons certify the answer. An earlier conjecture that 3SUM needs time in the real-RAM model was refuted by these results; the current conjecture asks only for .
Geometry: collinear points
3POINTS-ON-LINE: given points in the plane, are three of them collinear? The obvious algorithm checks all triples, ; sorting the slopes around each point gives , and duality plus line arrangements gives .
Reduction from 3SUM (Gajentaan and Overmars, 1995). Map each number to the point on the cubic curve. For distinct , the points are collinear iff
The map takes linear time, so an 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.
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 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 (; Pătrașcu, 2010, with randomized reductions both ways), and Exact Triangle in weighted graphs in its version with edges.
- Graphs and data structures: Pătrașcu (2010) used Convolution 3SUM to show that listing triangles in a graph with edges needs 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 never skip a valid pair ?
- Because the array has no duplicates
- 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
- Because it checks all pairs
- Because it uses hashing
In the reduction from 3SUM to collinear points, where is a number mapped?
What does the modern 3SUM conjecture claim?
- 3SUM needs time in every model
- No algorithm exists for any ; logarithmic speedups are allowed and known
- 3SUM is NP-hard
- 3SUM needs time
Which result shows that the comparison complexity of 3SUM is below ?
- Baran, Demaine and Pătrașcu (2005)
- Grønlund and Pettie (2014): decision trees of depth
- Gajentaan and Overmars (1995)
- Williams (2005)