Three lengths make a triangle when the two shorter sides together are longer than the longest one. Lengths 2, 3 and 4 work (2 + 3 > 4); 2, 3 and 6 don't (the two short sides can't reach across).
Checked naively, that's three inequalities for each of
triples. Sorting cuts it to one: once a ≤ b ≤ c, a + b > c is the
only check that can fail, because c is already the biggest.
One comparison, many triangles
Sort, and fix the largest side c. Now put two pointers on the
smaller values: L at the start, R just below c.
- Index 0: 2 (L)
- Index 1: 3 (✓)
- Index 2: 4 (✓)
- Index 3: 5 (✓)
- Index 4: 6 (R)
- Index 5: 7 (c)
2 + 6 > 7, and 2 is the smallest value in play. Swap it for any
value between L and R and the sum only grows, so all of them pair
with 6 too. That's R - L = 4 triangles counted in one step. Then
6 has been paired with everything that could work, so move R in.
When the sum is too small, the opposite holds: L is too short to
reach c even with the largest partner, so move L up.
| L | R | Sum vs 7 | Count | Move |
|---|---|---|---|---|
| 2 | 6 | 8, beats | +4 | R in |
| 2 | 5 | 7, ties | L up | |
| 3 | 5 | 8, beats | +2 | R in |
| 3 | 4 | 7, ties | L up, pointers meet |
Six triangles with 7 as the longest side. Then fix c = 6 and repeat
on the values before it.
Counting one at a time (count++, move R by one) throws the batch
away and slides back to . And keep the pointers strictly below
c's index, or c gets compared with itself.
Counting R − L at a time
time: one sweep per fixed side, which outweighs the sort. extra space.
This is 3Sum's fix-one-then-sweep shape with one twist: fixing the largest value instead of the smallest is what turns a single hit into a range you can count. The same trick solves 3Sum Smaller, which counts triples under a target.