Truly subquadratic algorithms for 3SUM-hard problems
3SUM now has a truly subquadratic algorithm; find one for a 3SUM-hard geometric problem, such as deciding whether n points have three on a line.

| 1 | """3SUM, the question itself: among n numbers, do three of them sum to zero? |
| 2 | |
| 3 | No data file: the figure makes a small instance (seeded) and solves it by brute force, keeping the first seed whose |
| 4 | instance has exactly one such triple, so the three numbers drawn really are the only answer. The numbers sit on the |
| 5 | line where they fall; the arcs walk from 0 by each of the three in turn and come back to 0. |
| 6 | """ |
| 7 | import random |
| 8 | from pathlib import Path |
| 9 | |
| 10 | import kit |
| 11 | |
| 12 | N, LO, HI = 18, -60, 60 |
| 13 | for seed in range(1000): |
| 14 | rnd = random.Random(seed) |
| 15 | nums = rnd.sample([v for v in range(LO, HI + 1) if v], N) |
| 16 | triples = [(a, b, c) for i, a in enumerate(nums) for j, b in enumerate(nums[i + 1:], i + 1) |
| 17 | for c in nums[j + 1:] if a + b + c == 0] |
| 18 | if len(triples) == 1 and min(abs(v) for v in triples[0]) > 8: |
| 19 | break |
| 20 | else: |
| 21 | raise SystemExit('no instance with exactly one triple') |
| 22 | a, b, c = sorted(triples[0]) |
| 23 | assert a + b + c == 0 |
| 24 | |
| 25 | base, X_ = 232.0, lambda v: 320 + v * (288 / HI) |
| 26 | body = kit.line(X_(LO - 4), base, X_(HI + 4), base, 'faint-s', 3) |
| 27 | body += kit.line(X_(0), base - 14, X_(0), base + 14, 'faint-s', 3) |
| 28 | # the walk: start at 0, step by each of the three in turn, and land back on 0 |
| 29 | walk = [0, c, c + a, 0] |
| 30 | for i, (p, q) in enumerate(zip(walk, walk[1:])): |
| 31 | y = base - 136 + 42 * i |
| 32 | head = 11 if q > p else -11 |
| 33 | body += kit.line(X_(p), y, X_(q), y, 'f-s', 5) |
| 34 | body += kit.path(f'M{kit.f1(X_(q) - head)} {kit.f1(y - 9)}L{kit.f1(X_(q))} {kit.f1(y)}' |
| 35 | f'L{kit.f1(X_(q) - head)} {kit.f1(y + 9)}', 'f-s', 5) |
| 36 | body += kit.line(X_(q), y + 6, X_(q), base - 14 if q else base + 14, 'faint-s', 2, |
| 37 | ' stroke-dasharray="3 6"') |
| 38 | body += ''.join(kit.dot(X_(v), base, 9, 'ink') for v in nums if v not in (a, b, c)) |
| 39 | body += ''.join(kit.dot(X_(v), base, 15, 'f') for v in (a, b, c)) |
| 40 | sums = f'{a}' + ''.join(f' + {v}' if v > 0 else f' - {-v}' for v in (b, c)) |
| 41 | label = f'{N} numbers · {sums} = 0 · the only triple' |
| 42 | kit.write(__file__, 'computer-science', body, label, |
| 43 | f'{N} numbers on a line; the only three of them that sum to zero are {a}, {b} and {c}') |
| 44 | print(label, 'seed', seed) |